Partner with experts to accelerate your digital transformation journey
Bobcares

How to Add hook_form_alter() in Drupal 8

PDF Header PDF Footer

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.

How to Add hook_form_alter() in Drupal 8

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.

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:

  1. All hook implementations from Module A
  2. Then from Module B
  3. Followed by any base theme(s)
  4. 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'];

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.
}
}

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.
}

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.
}

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);
}

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';
}

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

Submit a Comment

Your email address will not be published. Required fields are marked *

Get featured on the Bobcares blog and share your expertise with a global tech audience.

WRITE FOR US
server management

Spend time on your business, not on your servers.

TALK TO US

Or click here to learn more.

Speed issues driving customers away?
We’ve got your back!

Privacy Preference Center

Necessary

Necessary cookies help make a website usable by enabling basic functions like page navigation and access to secure areas of the website. The website cannot function properly without these cookies.

PHPSESSID - Preserves user session state across page requests.

gdpr[consent_types] - Used to store user consents.

gdpr[allowed_cookies] - Used to store user allowed cookies.

PHPSESSID, gdpr[consent_types], gdpr[allowed_cookies]
PHPSESSID
WHMCSpKDlPzh2chML

Statistics

Statistic cookies help website owners to understand how visitors interact with websites by collecting and reporting information anonymously.

_ga - Preserves user session state across page requests.

_gat - Used by Google Analytics to throttle request rate

_gid - Registers a unique ID that is used to generate statistical data on how you use the website.

smartlookCookie - Used to collect user device and location information of the site visitors to improve the websites User Experience.

_ga, _gat, _gid
_ga, _gat, _gid
smartlookCookie
_clck, _clsk, CLID, ANONCHK, MR, MUID, SM

Marketing

Marketing cookies are used to track visitors across websites. The intention is to display ads that are relevant and engaging for the individual user and thereby more valuable for publishers and third party advertisers.

IDE - Used by Google DoubleClick to register and report the website user's actions after viewing or clicking one of the advertiser's ads with the purpose of measuring the efficacy of an ad and to present targeted ads to the user.

test_cookie - Used to check if the user's browser supports cookies.

1P_JAR - Google cookie. These cookies are used to collect website statistics and track conversion rates.

NID - Registers a unique ID that identifies a returning user's device. The ID is used for serving ads that are most relevant to the user.

DV - Google ad personalisation

_reb2bgeo - The visitor's geographical location

_reb2bloaded - Whether or not the script loaded for the visitor

_reb2bref - The referring URL for the visit

_reb2bsessionID - The visitor's RB2B session ID

_reb2buid - The visitor's RB2B user ID

IDE, test_cookie, 1P_JAR, NID, DV, NID
IDE, test_cookie
1P_JAR, NID, DV
NID
hblid
_reb2bgeo, _reb2bloaded, _reb2bref, _reb2bsessionID, _reb2buid

Security

These are essential site cookies, used by the google reCAPTCHA. These cookies use an unique identifier to verify if a visitor is human or a bot.

SID, APISID, HSID, NID, PREF
SID, APISID, HSID, NID, PREF