Drupal Programming Trick – Add an element before/after another element in form_alter

Drupal Forms API (FAPI) provides hook_form_alter for modifying the contents of any form. This is possibly the most powerful feature that Drupal offers developers. It allows any module to change the form of any other module, thus allowing any custom/contrib modules to add or remove features from the UI of other modules.

If you want to add a form element to another module, write a custom hook_form_alter function. You have to insert your new form elements into the $form (or $form_values) array. The question is where and how? If you assume that $newform contains your new form element, here are some options:

    • $form_values
      ['your_variable'] = $newform will add it to the bottom after the buttons. This is never the right place to put a visible form element.
    • $form_values = array_merge($newform, $form_values) will add it the the beginning, but this is rarely the best place to put an element that extends another module.
    • $form_values = array_merge(array_slice($form_values, 0, 2), $newform, array_slice($form_values, 2)) will add it after the second element. But you shouldn’t rely on the form element positions being constant. The module you are extending could add new elements and other modules could add their own elements.
    • Use array_search to find a named element, and add your form element before or after the named element.
        // add the option before the buttons
      $pos = array_search('buttons', array_keys($form_values));
      $form_values = array_merge(array_slice($form_values, 0, $pos), $newform, array_slice($form_values, $pos));

      In the example above, you can replace ‘buttons’ with any other form element. While adding a new form element at the end just before the buttons is usually a good idea, the last element is also frequently named ‘submit’, or you might want to add this before some other element. Use print_r($form) to see the available form elements. If you want to be after that form element, set $pos = ... + 1.

The examples above assume that you have created $newform, which looks something like:

  $newform = array();
$newform['yourvalue'] = array(
'#type' => 'textifled',
'#title' => t('Your Value'),
'#default_value' => variable_get('yourvalue', 0), // or something
);

If you’re extending a settings form, the value will be saved as a Drupal variable using the form index name. That’s probably what you want to happen. But if you’re extending some other form, or you want some different behavior for handling your form element, you’ll need a submit handler:

  $form['#submit']['yourmodule_submit'] = array();
...
function yourmodule_submit($form_id, &$form_values)
2017-03-31T06:20:54+00:00 Categories: Drupal|

Share this

About the Author: