📜  drupal 7 hook_form_alter - PHP (1)

📅  最后修改于: 2023-12-03 15:30:34.156000             🧑  作者: Mango

Drupal 7 Hook_form_alter - PHP

As you might already know, Drupal is an open source content management system written in PHP. One of its key features is the ability to extend almost any core functionality or module using hooks. One of the most commonly used hooks is hook_form_alter, which allows you to modify and alter any Drupal form.

How does hook_form_alter work?

hook_form_alter is called every time a form is built. It allows you to add or remove elements from a form, modify the form's structure or display, and add new validation handlers or submit functions.

Creating a custom module to use hook_form_alter

To use hook_form_alter, you need to create a custom module. Here's how:

  1. Navigate to your Drupal installation's /sites/all/modules directory.
  2. Create a new directory called my_module.
  3. Inside this directory, create a file called my_module.module.
  4. In my_module.module, define the following function:
function my_module_form_alter(&$form, &$form_state, $form_id) {
  // Place your form-altering code here.
}
  1. Enable your custom my_module module from the Drupal administration interface.
Examples of using hook_form_alter
Changing the submit button's label and adding a new submit handler
function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id === 'my_form_id') {
    $form['actions']['submit']['#value'] = t('Update My Data');
    $form['#submit'][] = 'my_module_custom_submit_handler';
  }
}

function my_module_custom_submit_handler($form, &$form_state) {
  // Perform custom validation or submit logic here.
}
Adding a new field to a form and populating it with data
function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id === 'my_form_id') {
    $form['my_custom_field'] = array(
      '#title' => t('My Custom Field'),
      '#type' => 'textfield',
      '#default_value' => 'My Default Value',
    );
  }
}
Removing an existing field from a form
function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id === 'my_form_id') {
    unset($form['my_field_to_remove']);
  }
}
Conclusion

hook_form_alter is a powerful tool that can be used to modify the behavior and appearance of Drupal forms. Whether you need to add new fields, alter existing ones, or modify form submission behavior, hook_form_alter can help you achieve your goals. With the examples presented here, you should be well on your way to mastering this essential Drupal hook.