Quick Tip: Adding a Reset button to a Drupal form

Using hook_form_alter one can easily add a "Reset" button to a Drupal form.

Here's a simple example:

/**
 * Implementation of hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'myform':
      $form['buttons']['reset_button'] = array(
        '#type' => 'markup',
        '#value' => '',
        '#weight' => 2000,
      );
      break;
  }
}

It may not be appropriate for you to put your new reset element into the buttons array. Use dpm() (part of the Devel module) to show what $form looks like. If you don't understand this, and the code above isn't working for you, you may try $form['reset_button'] = array....

Adjust the value of #weight to move the button around the form. dpm($form) will show you weights (if any) of existing elements so you can make educated decisions about the weight of your new field.

One last note about the '#type' => 'markup' line: this is not a requirement, but I like to include it for clarity.

Tags: 

Add new comment