[Drupal] How to avoid the form validation for Back button in drupal forms

| | 1 min read

In the cases of multi-stage form it is necessary to add a Back button to the forms to navigate to the previous forms. By limiting the validation errors for a submit button, we can skip the form validation for that submit button.

While creating a Back button we can specify an attribute called "#limit_validation_errors", and can bet set to an array of form elements to validate. So when the Back button is clicked, only the specified form elements are validated. In order to skip the form validation, we can set an empty array to the attribute.

The following example shows the usage.

Consider a form


 'textfield',
    '#title' => t('Your Name'),
    '#required' => TRUE,
  );
  $form['next'] = array(
    '#type' => 'submit',
    '#value' => 'Next',
    '#submit' => array('my_module_my_form_submit'),
  );
  $form['return_back'] = array(
    '#type' => 'submit',
    '#value' => 'Back',
    '#submit' => array('my_module_my_form_return_back_submit'),
    '#limit_validation_errors' => array(),
  );
}

In this form the textfield "name" is a required field. So when the "Next" submit button is clicked, "name" field is validated. As we specified the #limit_validation_errors with empty array in "return_back" submit, it will not validate the "name" field.

By using the #limit_validation_errors we can limit the form validation to the specified form elements only. It will be helpful in multi-stage forms.

 

 

?>