【问题标题】:Drupal 7 - How to check if a particular field has a value - sql query?Drupal 7 - 如何检查特定字段是否有值 - sql查询?
【发布时间】:2013-01-31 09:31:04
【问题描述】:

我正在尝试编写 PHP 代码来验证字段中的表单输入。如果该字段已经有值,系统必须发送一条错误消息。如果没有值或值与输入相同,则可以提交表单。 编辑后的代码是:

/**
* Implement a function to get the ID and the title of the referenced node
* of type Reservation
* by the nodereference field called Period
* in the currently edited node from type Board
* Try to do this by the node_load() instead of the database query
* Is it the correct method to get the edited node's ID?
**/
function period_get_value() {
$thisnodeboard = $node->field_period_1[$node->language][0]['nid'];
$reservationrec = node_load(array('nid'=>$thisnodeboard));
return $reservationrec->title;
}
/**
* Implement the hook_form_FORM_ID_alter function to validate
* if the field Period has already value set
* and if there is such to check if it is the same as the input value
**/
function period_validate_form_slickgrid_editor_form_alter(&$form, $form_state){
/**
* The current value is the title of the referenced node
**/
$valcurr = period_get_value();
$valnew = $form_state['values']['field_period_1'];
if (isset($valcurr)&&($valcurr!=$valnew)){
    form_set_error('field_period_1', t('There is already value set for this field'));
  }
return $form;
}

但它仍然不起作用 - 不设置任何消息并允许更改 field_period_1 中的现有值。

【问题讨论】:

    标签: sql validation drupal field


    【解决方案1】:

    首先,在 D7 中编写手动 SQL 查询绝对是最后的手段。

    好的,所以您实际上只想阻止用户在创建节点后更新字段。

    你可以做两件事之一。如果您只想阻止从节点/编辑表单进行编辑,您可以实现 hook_form_FORM_ID_alter() 然后添加您自己的验证或提交处理程序。然后,您将验证该字段是否未更改并采取相应措施。

    如果您想防止它在任何地方发生,例如以编程方式。您可以实现 hook_node_update() 并检查 $node->is_new 和 $node->type 以防止更改非新节点。

    【讨论】:

    • 您好,我知道编写 SQL 是不得已而为之,但恐怕我已经到了那个地步。我尝试了每个提供字段验证的模块(或几乎每个模块),但没有一个对我的任务有用。我也尝试过 Unique 字段,但它只是设置了字段值的唯一性,因为我必须设置一个字段值,每次我尝试更改该值时,都会出现一条消息并警告我已经存储了数据这个领域。好的,这就像在设置初始值后锁定字段一样。我希望我能足够清楚地解释我的问题:) 你能帮我吗?
    • 确认。您希望字段值在整个内容类型中是唯一的吗?
    • 不,它不必是唯一的 - 在创建节点并填充一次字段后,字段值很可能无法更改。至少当管理员试图更改字段值时系统必须设置警告消息,并且不允许提交带有新字段值的表单。
    • 答案已更新。如果您有任何问题,请查看代码并回复。
    • 我必须在自定义模块中实现 hook_form_FORM_ID_alter() 吗?我已经阅读了文档,但是因为在不知道如何添加提交处理程序之前从未实现过该功能。任何线索从哪里开始?并感谢您的帮助和花费的时间!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-22
    • 2010-09-28
    • 1970-01-01
    • 1970-01-01
    • 2015-09-03
    相关资源
    最近更新 更多