用于比较两个字段值的字段验证

时间:2018-03-27 07:52:51

标签: php drupal

我使用两个字段“capacity”和“count”创建了一个内容类型。

在自定义模块中,我想验证字段“count”应小于字段“capacity”。

SELECT Component_ID, IFNULL( total,0) replacements FROM
            (
              SELECT Component_ID, COUNT(*) total
                   FROM component_replacements GROUP BY Component_ID
            ) replacements ON components.Component_ID = replacements.Component_ID

1 个答案:

答案 0 :(得分:3)

首先添加自定义验证函数,然后从那里激活逻辑,并在必要时阻止表单进一步处理。将MYMODULEMYCONTENTTYPE替换为您的计算机名称。

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function MYMODULE_form_node_form_alter(&$form, &$form_state, $form_id) {

  // Find the content type of the node we are editing.
  $content_type = $form['#node']->type;

  if ($content_type == 'MYCONTENTTYPE') {

    // Add an additional custom validation callback.
    $form['#validate'][] = 'MYCUSTOM_FORMVALIDATION';
  }
}

/**
 * Custom MYCONTENTYTPE node form validation.
 */
function MYCUSTOM_FORMVALIDATION($form, &$form_state) {

  // Better check isset() and !empty() first. Depends on your needs.
  // Convert values to comparable numbers.
  // Maybe you prefer intval() or some other logic. Depends on your needs.
  $field_a = floatval($form_state['values']['field_a'][LANGUAGE_NONE][0]['value']);
  $field_b = floatval($form_state['values']['field_b'][LANGUAGE_NONE][0]['value']);

  // Stop the form from further processing if field A < than field B.
  if ($field_a < $field_b) {
    form_set_error('stop', t('Field A shall be greater then Field B'));
  }
}