Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By Amjad_dokhan on
Dear everyone,
I've been struggling for almost a week now trying to learn how to implement hook_form_alter in Drupal 8. I've got the Form API module from the examples module and I've been trying to insert hook_form_alter there but Drupal doesn't even see this function.
The routing file looks like this:
fapi_example.description:
path: 'examples/fapi-example'
defaults:
_controller: '\Drupal\fapi_example\Controller\Page::description'
_title: 'Form API Examples'
requirements:
_permission: 'access content'
fapi_example.simple_form:
path: 'examples/fapi-example/simple-form'
defaults:
_form: '\Drupal\fapi_example\Form\SimpleForm'
_title: 'Simple Form API Example'
requirements:
_permission: 'access content'
And I have my hook_form_alter function like this:
function fapi_example_simple_form_form_alter(&$form, &$form_state) {
$form['title']['#title'] = t('ANYTHING HERE!');
kint($form);
}
So where exactly should I implement the above function? Inside the controller file or inside the Form file. Should it be a method of in the class that extends FomBase or where? I appreciate any help available. Thank you all in advance.
Comments
All hooks go in the .module
All hooks go in the .module file, including hook_form_alter(). But that isn't your only problem.
Your function definition is incorrect. Take a look at the API page: hook_form_alter()
The function definition looks like this:
You are using Drupal 7 style, which is why it isn't being picked up. In Drupal 8, $form_id is not an array, it's an object of type FormStateInterface.
Hi Jaypan,
Hi Jaypan,
I thought that we didn't use the .module format in Drupal 8 anymore. I got the impression (from the videos I've watched) that the new method of writing a module was to use .routing.yml and Controller.php files only. I guess I was mistaken. I also got the (&$form, &$form_state) from this Drupal link:
https://www.drupal.org/docs/8/api/form-api/introduction-to-form-api
which I also guess is typo !
Anyway. Thank you very much again Jaypan. You've been very helpful as always. Have a good day !
.module files are still used
.module files are still used in Drupal 8, they just aren't required, like they were in Drupal 7. This is because modules may have no hooks, and therefore no need for a .module file.
I just went and edited the module page you pointed there. It was either a typo by someone who wrote the page, or maybe it was written early in the days of D8 before FormStateInterface was introduced.