1

I want to use custom validation while adding a term. I used form alter and #validate function it's not working.Default validation function under taxonomy module is working but my custom validate function is not.

Here is my code

  function lms2_validate_form_alter($form , &$form_state, $form_id){

    if ($form_id == 'taxonomy_form_term'){          
      $form['#validate'][] = 'lms2_validate_term_validate';
    }
  } 

  function lms2_validate_term_validate($form ,&$form_state){
      drupal_set_message('hello');
  }  

2 Answers 2

0

This would solve your problem for sure. However I would recommend you to have a look at hook_form_FORM_ID_alter

It is recommended to use hook_form_FORM_ID_alter if your module is implementing the hook only for a couple of forms or so. It gives better performance as it is being invoked only for the particular form and not for all and then checking it in if/else or switch/case loop.

Example: Considering your module name is: lms2_validate

function lms2_validate_taxonomy_form_term_alter(&$form, &$form_state, $form_id) {
 $form['#validate'][] = 'lms2_validate_term_validate';
}

function lms2_validate_term_validate($form, &$form_state) {
 drupal_set_message('hello');
}

NOTE: There is no if/else loop needed.

1
  • You probably mean 'lms2_validate_form_taxonomy_form_term_alter.
    – jiv-e
    Nov 12, 2015 at 14:41
2

In Drupal 7, if you go through hook_form_alter.

It uses $form as a reference. You need to use & before $form.


/**
 * Implements hook_form_alter
 */
function hook_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'taxonomy_form_term': 
      $form['#validate'][] = 'mymodule_taxonomy_form_custom_validate';
      break;
  }
}
/**
 * Implements hook_form_validate
 */
function hook_taxonomy_form_custom_validate($form, &$form_state) {
  //validation goes here
}

Let say if your module name is lms2_validate then use:


function lms2_validate_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'taxonomy_form_term') {
    $form['#validate'][] = 'lms2_validate_term_validate';
  }
}

function lms2_validate_term_validate($form, &$form_state) {
  drupal_set_message('hello');
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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