Drupal 7 form cancel button

Print

When creating a form it is often required to make a cancel or back button, but this provides a number og issues with form validation but fortunetly there is a way to prevent these issues.

Create your cancel or back button.

  1. $form['actions']['back'] = array(
  2.   '#type' => 'submit',
  3.   '#value' => t('Back'),
  4. );

You can use either type: submit, image_button or button. In order to prevent validation of the form elements you need to add #limit_validation_errors and #submit to the element.

  1. $form['actions']['back'] = array(
  2.   '#type' => 'submit',
  3.   '#value' => t('Back'),
  4.   '#limit_validation_errors' => array(),
  5.   '#submit' => array('example_form_submit'),
  6. );

#limit_validation_errors contains an array of elements to validate on submit and since it is empty in this case nothing is validated

In order for #limit_validation_errors to work you also need to specify a submit function to call otherwise the element attribute is ignored.

Category: 

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.