Modifying Forms Using Alter Hooks
The ability of themes to use alter hooks is new in Drupal 7. Templates are great for situations where you want to have a lot of control over the markup itself, but there are quite a few situations where simply using
hook_form_alter() can make things a lot easier, especially if you are comfortable with Drupal’s form markup either by default, or in combination with changes you can make site-wide via theme functions. Using an alter hook is perfect for quick changes like:
- Simple changes to form labels, descriptions, and other properties.
- Changing the order in which the form elements print using the
- Wrapping a few elements in a
- Hiding or removing form elements that are not required.
- Adding some markup to a form.
It’s also arguably easier because there are fewer steps involved in the process. You don’t need to implement
hook_theme(). You also get full control over the elements. There are certain limitations to the changes you can make within theme functions, as it’s already too late in the process.
hook_form_alter(): Runs for all forms.
hook_form_FORM_ID_alter(): Runs for a specific form ID.
There are reasons for using
hook_form_FORM_ID_alter() all the time, but those reasons mainly apply to the tasks a module developer needs to perform. Unless you are specifically targeting more than one form to do the same thing, as shown in Listing 16–34, it’s probably best to use
hook_form_FORM_ID_alter(), as shown in Listing 16–35.