Programmatically modifying a webform with hook_form_alter()

Last updated on
30 April 2025

A webform node will respond to a call to hook_form_alter() just like any other form built with the Form API.

However, the structure of the node is different from your average form and can catch you out.

hook_form_alter() will provide you with three things with which to work: the $form variable itself, the form's unique identifier and $form_state, which will include any submitted values. $form is the container for the form components, so that is where to look to make your modifications.

To alter only webforms, implement HOOK_form_webform_client_form_alter(). To alter a specific webform, using webform 7.x-4.4 or later, implement HOOK_form_webform_client_form_NID_alter().

The structure of $form

Form is an array of associative arrays, just like so much of Drupal's internal workings. However, if you take a look at it via print_r() or dpm(), and take a quick glance down through the variable's structure, you will see no obvious collection of form elements.

You could be forgiven for looking at $form['#node']->webform['components'], but that will yield no results.

The actual form components you need to modify will be found in $form['submitted']. This will give you an array of form elements, each an array of properties and options. This is where you can modify to get results.

Example

Drupal 7


function mymodule_form_alter( &$form, &$form_state,$form_id ){
  // this is for your developer information and shows you the
  // structure of the form array
  dpm($form);
  // this will give you the details for my_form_component
  $a_component = $form['submitted']['my_form_component'];
  dpm($a_component);
  
  // you'll want to limit your altering to specific forms
  if ($form_id == 'my_webform_client_form_id') {
    // edit component values like this:
    $form['submitted']['my_form_component']['#title'] = 'A spurious text title';
  }
}

Drupal 6


function mymodule_form_alter($form, &$form_state,$form_id) {
  // this is for your developer information and shows you the
  // structure of the form array
  dpm($form);
  // this will give you the details for my_form_component
  $a_component = $form['submitted']['my_form_component'];
  dpm($a_component);
  
  // you'll want to limit your altering to specific forms
  if ($form_id == 'my_webform_client_form_id') {
    // edit component values like this:
    $form['submitted']['my_form_component']['title'] = 'A spurious text title';
  }
}

Help improve this page

Page status: Not set

You can: