Skip to main content
Image
Hooks drupal

How to implement hook form alter in Drupal

If you are one of those who love to customize every corner of your website, today I bring you a theme that you will love: hook_form_alter and its variants. This powerful hook is like Drupal's anonymous superhero, always ready to modify forms without making much noise. But don't worry, here we are going to bring it out of the shadows and show you how to use it like a real expert. 

What is hook_form_alter?

In simple terms, hook_form_alter is a function or β€œhook” that allows you to modify any form in Drupal before it is rendered. Do you want to add an extra field? Change a button? Or even remove something you don't need? With this hook, you have control.

Drupal has several variants of this hook, depending on the level of precision you need:

  1. hook_form_alter: the most generic, it affects all the forms; although by means of the $form_id parameter you can make conditions for a particular form.
  2. hook_form_FORM_ID_alter: more specific, only alters a form with a particular ID.
  3. hook_form_BASE_FORM_ID_alter: for forms that share a common base (such as nodes or users).

Why use hook_form_alter?

Imagine this: you have a standard contact form, but you want to add a custom field for users to select their favorite department (because, well, who doesn't love picking things?). Instead of creating a module from scratch or hacking the code base (don't do it!), you can use hook_form_alter to do it cleanly.

In addition, this hook is ideal for:

  • Add custom validations.
  • Modify labels, placeholders or field attributes.
  • Hide unnecessary elements.
  • Inject JavaScript or CSS specific to a form.

A Practical Example: customizing a form

Let's get into the action with a simple but useful example. Suppose we want to modify the content creation form of a node type called β€œArticle” (node_article_form) to add a message to the user.

Step 1: Create a Custom Module

If you don't have a custom module, create one. For example, let's call it my_module. Here are the basic steps:

  1. Create a folder called my_module inside /modules/custom.
  2. Inside that folder, create two files:
    • my_module.info.yml : Defines the module.
    • my_module.module : Here we will write our code.

The my_module.info.yml file might look like this:

name: 'My module'
type: module
description: 'A module to customize forms.'
core_version_requirement: ^8 || ^9 || ^10
package: Custom

Paso 2: Implementar hook_form_alter

Now, open the file my_module.module and write the following:

<?php

/**
 * @file
 * Contains functions of the My module.
 */

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function my_module_form_node_article_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Add message to form.
  $form['motivacion'] = [
    '#markup' => '<p style="color: green;">Writing an article on Drupal Sapiens!</p>',
    '#weight' => -10, // We place it at the beginning of the form.
  ];

  // We change the text of the send button.
  $form['actions']['submit']['#value'] = t('Publish article');
}

Step 3: Activate the Module

Go to the module admin page ( /admin/modules ) and activate "My Module". Now, when you go to create a new article, you will see a message just above the form and the submit button will say "Publish article".

Variantes de hook_form_alter

As I mentioned before, there are different ways to use this hook depending on how much reach you want to have. Here I explain briefly:

  • hook_form_alter : If you want to alter all forms, use this variant. It's like casting a giant net. For example:
function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'user_login_form') {
    $form['mensaje'] = ['#markup' => '<p>Welcome back!</p>'];
  }
}
  • hook_form_FORM_ID_alter: ideal for modifying a specific form. As in our previous example, we use hook_form_node_article_form_alter.
  • hook_form_BASE_FORM_ID_alter: useful if multiple forms share a common base. For example, all node forms have BASE_FORM_ID equal to node_form. This way you can alter multiple forms at once.

Final Tips

  1. Use Devel to debug: If you're unsure of a form's ID, install the Devel module and use dpm($form_id) inside hook_form_alter to find out.
  2. Don't overload your forms: Although it's tempting to add a thousand things, remember to keep your forms clean and functional.
  3. Test your changes: Always test your modifications in a development environment before pushing them to production. No one wants to accidentally break a critical form.

Conclusion

hook_form_alter is an incredibly versatile tool that allows you to customize Drupal forms without breaking a sweat. Whether you want to make small tweaks or larger transformations, this hook is your best friend.

So next time you need to modify a form, don't hesitate to pull hook_form_alter out of your toolbox. And remember, with great power comes great responsibility!

Do you have any questions or any cool tricks you've made with hook_form_alter ? Leave us a comment below!

Tags

Join the Drupal Sapiens Community

Save content that interests you, connect with others in the community, contribute to win prizes and much more.

Login or create an account here

Latest posts

Featured

Last news