Using hook_form_BASE_FORM_ID_alter()

hook_form_alter() is the go-to function for making changes to forms that are used across Drupal. We all use it. We all love it.

But since Drupal 7, you can also use a variant of this function: hook_form_BASE_FORM_ID_alter(). Here's a simple visual of how it works: 

All drupal forms can be divided into subsets, like comment forms or node-edit forms.

hook_form_alter() fires on all Drupal forms (the big circle). With hook_form_BASE_FORM_ID_alter(), you can restrict it to firing on a subset of forms (one of the smaller circles), which can save Drupal some processing. (to get even more specific, you could target a single form by using hook_form_FORM_ID_alter(), but I'll leave that discussion for another day).

You can find the Base Form ID by printing out the $form_state variable in a normal hook_form_alter, like so:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  // You must enable the devel module in order to use this function.  
  dpm($form_state); // Prints $form_state to the page.  
}

The "base_form_id" is tucked away in the "build_info" array.

The base form id is tucked away in the build_info array.

If you want to implement hook_BASE_FORM_id_alter, here is a simple example:

function mymodule_form_node_form_alter(&$form, &$form_state, $form_id) {
  // Find the content type of the node we are editing.
  $content_type = $form['#node']->type;
  if ($content_type == 'article') {
    // Alter the 'article' form here.
  }
}

As you can imagine, these tools aren't worth much if you don't know which Base Form ID's are out there. I dug around Drupal core a bit and these are the ones I was able to find.

Base Form IDs in Drupal 7:

  • node_form --- for node edit forms
  • comment_form --- for comment forms

    Base Form IDs in Drupal 8

    (as of August 16, 2013)

  • node_form --- for node edit forms
  • comment_form --- for comment forms
  • menu_form --- for menu forms
  • menu_link_form --- for menu link forms
  • node_type_form --- for content type forms
  • custom_block_form --- for custom block forms
  • taxonomy_term_form --- for taxonomy term forms
  • contact_category_form --- for site-wide contact category forms
  • date_format_form --- for date/time format forms
  • image_style_form --- for image style forms
  • filter_format_form --- for text format forms
  • view_form --- for views forms
  • custom_block_type_form --- for block type forms (new in Drupal 8)
  • form_mode_form --- for form mode forms (new in Drupal 8)
  • view_mode_form --- for view mode forms (new in Drupal 8)

    Base Form IDs in major Contrib modules:

  • webform_client_form --- for webforms (from the webform module)

    As you can see, the API is implemented most thoroughly in Drupal 8. If you know about ones that I missed, just mention them in the comments below and I'll add them to the list.

  • Comments