user731060
user731060

Reputation: 47

Skip the validation for the "button" form field

I am devloping a web app using Drupal. My form contains two buttons, "Submit" and "Clear." If When click the "Clear" button, I want to skip all the validations, including the required field validation. Is there any way to accomplish this?

Upvotes: 0

Views: 1735

Answers (2)

user1165759
user1165759

Reputation: 333

When I need a form reset button this is what I do.

In your form (or form_alter) code add the following:

`$form['clear'] = array(
          '#name' => 'reset',
          '#type' => 'submit',
          '#value' => t('Reset'),
          '#id' => 'edit-reset-button',
          '#validate' => array('form_clear'),
      );`

Add the clear function (uses a simple unset and redirect):

`function form_clear($form, &$form_state) {
   $form_state['rebuild'] = TRUE;
   unset($form_state['values']);
   drupal_goto($form['#action']);
 }`

Upvotes: 1

avpaderno
avpaderno

Reputation: 29748

There is a way to accomplish what you are trying to do, but it works only with Drupal 7: When you define the "Clear" form field, add the following line.

'#limit_validation_errors' => array()

The documentation for that property describes it as:

Provides an array of sections which are parts of $form_state['values'] which should be validated, implying that sections which are not listed should not be validated. This is normally used in multistep forms in the case of a "back" button, for example, where '#limit_validation_errors' => array() would mean not to validate anything as form values on the current page are to be discarded anyway.

The example made from the documentation is about a "Back" button, but the same applies to the "Clear" button in your case, as all the entered values are discarded, and it doesn't make sense to report errors for values that are not used.

Drupal 6 doesn't use that form-field property.
There isn't a way to avoid values are validated, especially if there are values that are marked as required. You could not mark those values are required, and rendering the form fields to include a red asterisk (which is the Drupal way to mark required values), but then you should write a validation handler for the other button that would verify the required values are entered.

Upvotes: 0

Related Questions