Discover how to add hook_form_alter() in Drupal 8. Our Drupal Support team is ready to assist.
How to Add hook_form_alter() in Drupal 8
One of the most powerful features of Drupal is its hook system. It allows developers to extend and alter existing behavior without hacking core code. Among these, `hook_form_alter()` and its variants are widely used to modify form behavior, add or remove elements, apply custom validation, and more.
Today, we will walk through the order of form alteration hooks, practical examples of how to use them, and debugging tips to make the form customizations effective and efficient.
An Overview:
Understanding the Order of Form Alter Hooks
When a form is created in Drupal, various modules and themes can implement hooks to alter it. These hooks are called in a specific order:
- hook_form_alter()
- hook_form_BASE_FORM_ID_alter()
- hook_form_FORM_ID_alter()
These hooks are called within each module, and for each module, the more general hooks are invoked first, followed by the more specific ones. For example:
- hook_form_alter() is called for all forms.
- hook_form_BASE_FORM_ID_alter() targets forms that share a base form ID.
- hook_form_FORM_ID_alter() is used to target a specific form.
The complete calling order is:
- All hook implementations from Module A
- Then from Module B
- Followed by any base theme(s)
- And finally, the current theme
Furthermore, module execution order is based on system weight and module name.
Facing deprecated warnings in your forms? Here’s how to hide deprecated warning in Drupal.
A Common Use Case: Altering the Node Form
A frequent scenario is adding or modifying fields on the node form. We can access the node object like this:
$form['#node'];
Copy Code
To alter the node form in the custom module, use:
use Drupal\Core\Form\FormStateInterface;
/
* Implements hook_form_alter().
*/
function yourmodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if ($form_id == 'node_article_edit_form' || $form_id == 'node_article_form') {
// Modify the node article form here.
}
}
Copy Code
Also, always clear the cache after writing hook functions to make Drupal recognize them.
Use the `drush cr` command (if you’re using Drush 8+) or go to Manage > Configuration > Performance > Clear All Caches.
If you’re using Plesk for hosting, check out how to set up Drupal with Plesk.
Debugging Tips: Is Your Hook Being Called?
To verify if the hook is working, we can use the Devel module along with Kint, a debugging tool that prints structured variable output.
Install and enable both modules, then in the hook, use:
function yourmodule_form_alter(&$form, &$form_state, $form_id) {
kint($form); // This prints all form variables.
}
Copy Code
To target a specific form like `node-question-form`:
function yourmodule_form_node_question_form_alter(&$form, &$form_state, $form_id) {
kint($form); // Debug the specific form.
}
Copy Code
Alternatively, we can use `echo` or `print_r()` and check the browser’s source code using `Ctrl+F` to locate the debug text.
Tip: Learn how to troubleshoot AJAX errors on file upload in Drupal.
Practical Example: Forcing Sort Order in an Exposed Views Form
Here’s how to control the sort direction of a Views exposed filter based on the user’s selection:
function MYTHEME_form_alter(&$form, &$form_state, $form_id) {
if ($form_id !== 'views_exposed_form' || $form['#id'] !== 'views-exposed-form-search-custom-page-1') {
return;
}
$user_input = $form_state->getUserInput();
if (empty($user_input['sort_by'])) {
return;
}
if ($user_input['sort_by'] == 'relevance') {
$user_input['sort_order'] = 'ASC';
} elseif ($user_input['sort_by'] == 'created') {
$user_input['sort_order'] = 'DESC';
}
$form_state->setUserInput($user_input);
}
Copy Code
Replace `”views-exposed-form-search-custom-page-1″` with the actual form ID, and ensure that `”relevance”` and `”created”` match the sort field machine names.
Altering Forms in Custom Themes
If we are working within a custom theme, we can use the following format in your `THEMENAME.theme` file:
function bootstrap_ga_form_user_login_form_alter(&$form, &$form_state, $form_id) {
$form['#validate'][] = '_bootstrap_ga_form_user_login_form_validate';
}
Copy Code
In this case, `bootstrap_ga` is the name of the custom theme. This example adds custom validation to the user login form.
[Need assistance with a different issue? Our team is available 24/7.]
Conclusion
Modifying forms in Drupal using hook functions is a core part of custom module and theme development.
In short, our Support Engineers demonstrated how to add hook_form_alter() in Drupal 8.
0 Comments