📅  最后修改于: 2023-12-03 15:30:34.156000             🧑  作者: Mango
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.
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.
To use hook_form_alter, you need to create a custom module. Here's how:
/sites/all/modules
directory.my_module
.my_module.module
.my_module.module
, define the following function:function my_module_form_alter(&$form, &$form_state, $form_id) {
// Place your form-altering code here.
}
my_module
module from the Drupal administration interface.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.
}
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',
);
}
}
function my_module_form_alter(&$form, &$form_state, $form_id) {
if ($form_id === 'my_form_id') {
unset($form['my_field_to_remove']);
}
}
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.