Drupal 7 - 如何检查特定字段是否有值 - sql查询?

时间:2013-01-31 09:31:04

标签: sql validation drupal field

我正在尝试编写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中的现有值。

1 个答案:

答案 0 :(得分:0)

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

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

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

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