Practical Drupal Development #3 - How to alter forms by using hook form FORM_ID alter

Drupal

This is the episode number three of Practical Drupal Development. This time I'm going to show you how to modify any webform in Drupal by using a hook called hook_form_FORM_ID_alter. As always, I'm going to pose a practical issue in order to help you understand how this hook works.

Issue to be solved

Imagine that you are reported to alter the label for the text field of the Search module. This label is set to Enter your keywords by default and you'd need to change that value to, for example, Please enter the keywords.

Label for the text field of the Search module

hook_form_FORM_ID_alter

Although you could use hook_form_alter, this may best be done by using hook_form_FORM_ID_alter, since it provides a shortcut for making alterations based on the form id. But... How can you know the id of a particular form? You can know the id of a particular form by using a module called Devel, so install it, check Display $page array on the configuration page and save the changes.

Setting Display $page array marked on the configuration page of the Devel module

Now you are ready to search for the id of the Search form. Please go to the page for the Search module (/search/node) and you will see a green box in the messages area of the page. In this box there is a multidimensional array containing a lot of information related to the elements of the current page, so you have to explore it in order to find the Search form id.

Multidimensional array containing the form id for the Search form

As you can see in the previous image, there is a key called #form_id that has a value of search_form. That is the id you are searching for. Now you have to search for the key/value pair storing the string for the label used by the text field of the Search module. This key/value pair falls under the subarray called keys as you can see in the next image.

key/value pair storing the string for the label used by the text field of the Search module

OK, now you have all the information that you need to write the code for the hook in the template.php file.

/**
 * Implements hook_form_alter().
 */
function yourthemename_form_search_form_alter(&$form, &$form_state) {

  $form['basic']['keys']['#title'] = 'Please enter the keywords';

}

"Hey! what happens if I want to remove the label. I mean... I don't want the label to be displayed before the text field of the Search form."

As with the title, you must search for the right key/value pair to make the label invisible. This key/value pair is #title_display → before (you can see it in the previous image) and the body for the hook would be as follows:

/**
 * Implements hook_form_alter().
 */
function yourthemename_form_search_form_alter(&$form, &$form_state) {

  $form['basic']['keys']['#title_display'] = 'invisible';

}

If you want to go further on hook_form_FORM_ID_alter, you can read the information provided by the Drupal API.