Warning message

Documentation is currently being migrated into the new system. Some pages might be temporarily missing, and some guides might appear empty. Thank you for your patience while we are improving Drupal.org documentation.

Forms API - Modify Forms with hook_form_alter()

Last updated on
October 14, 2016 - 20:46

Drupal 7 forms that modules create can be changed by other modules and even themes with the help of Drupal FAPI hooks system. See Drupal 7 Hooks for a list of Drupal system hooks. The hook that allows to edit the existing forms is hook_form_alter. See the hook_form_alter() documentation at Drupal API site.

The syntax is hook_form_alter(&$form, &$form_state, $form_id).

In this hook call, $form is the array of form elements (see Drupal 7 Form API Overview article). $form_state has the keyed array of the state of the form, that can change on form submission or in multi-step forms. And an important parameter is $form_id, which has in it the unique name of the form. Drupal core will cycle through all the registered forms, passing their initial array, state, and unique id to this hook function.

Example:

For example, you wrote a module mymodule that needs to add a checkbox "I certify that this is my true name" to a small form with a name and a submit button from the Drupal 7 Form API Overview article.

<?php
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  // Check when the right form is passed
  if ($form_id == 'module_formname') {
    
    // Add the check box
    $form['certify'] = array(
      '#type' => 'checkbox',
      '#title' => t('I certify that this is my true name'),
    );
  }
}
?>

We can not only add items to a form this way, but also remove existing elements, assign additional attributes to the elements, or edit the attributes of existing elements as well.