0

I am adding a custom validation handler to the node edit form, using the following code.

function my_module_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id != 'node_article_edit_form') {
    return;
  }   

  // ...

  $form['#validate'][] = 'my_module_node_article_edit_form_validate';
}

function my_module_node_article_edit_form_validate(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  // ...
}

The validation handler is not invoked, though. What is wrong with the code I am using?

0

3 Answers 3

4

Validate and submit handlers can be placed on the form level or on specific buttons. If they are defined on a button, only those will be executed; it only falls back to the top-level if nothing is defined on the pressed button.

The node form, like all entity forms has the callbacks defined on the button, which is complicated by the fact that there are multiple buttons (save as published, save as unpublished and so on). You must define your validate callback on all of them.

Also, for validation of an entity, you should instead use validation constrains on the fields or the entity.

2

Try Like this

/**
  * Implements hook_form_FORM_ID_alter().
  */
  function MYMODULE_form_FORM_ID_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){
    $form['#validate'][] = 'MYMODULE_validate';
 }


/**
 * Implements custom validate.
 */
function MYMODULE_validate(array &$form, FormStateInterface $form_state){
// YOUE CODE GOES HERE
}
0

On Drupal node edit forms, the validation handlers are defined at button level, so the code should assign the new validation handler to $form['actions']['submit']['#validate'][].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.