Showing posts with label Form Alter in Drupal. Show all posts
Showing posts with label Form Alter in Drupal. Show all posts

Tuesday, May 17, 2011

Form Alter in Drupal

Perform alterations before a form is rendered.

One popular use of this hook is to add form elements to the node form.

Note that instead of hook_form_alter(), which is called for all forms, you can also use hook_form_FORM_ID_alter() to alter a specific form.

Syntax: 
Drupal 4.7 – 5 hook_form_alter($form_id, &$form)
Drupal 6 – 8 hook_form_alter(&$form, &
$form_state
, $form_id)


Example #1: 

function addons_form_alter (&$form, &$form_state, $form_id) {

    if($form_id == 'menu_edit_item') {  
  
    // move submit to the end
    $form['submit']['#weight'] = 5;
    
    $form['additional_title'] = array(
        '#type' => 'textfield',
        '#title' => t('Additional Title'),
        '#maxlength' => 180,
        '#required' => TRUE,
        '#default_value' => $externalLinks->title,
        '#description' => 'Name of the Additional title'
      );
    }
 
}



/* using hook_form_FORM_ID_alter */

Provide a form-specific alteration instead of the global hook_form_alter().
Modules can implement hook_form_FORM_ID_alter() to modify a specific form, rather than implementing hook_form_alter() and checking the form ID, or using long switch statements to alter multiple forms.
Note that this hook fires before hook_form_alter(). Therefore all implementations of hook_form_FORM_ID_alter() will run before all implementations of hook_form_alter(), regardless of the module order.
 
Syntax:


6 hook_form_FORM_ID_alter(&$form, &$form_state)
7 – 8 hook_form_FORM_ID_alter(&$form, &$form_state, $form_id)

Example #2:
function addons_form_menu_edit_item_alter (&$form, &$form_state) {
 
    // move submit to the end
    $form['submit']['#weight'] = 5;
    
    $form['additional_desc'] = array(
        '#type' => 'textfield',
        '#title' => t('Additional Description'),
        '#maxlength' => 180,
        '#required' => TRUE,
        '#default_value' => $externalLinks->title,
        '#description' => 'Name of the Additional Description'
      );
 
}

Followers