Altering other forms
Drupal's Form API does not just provide a way to create forms. There are ways to alter forms through a custom module that allows you to manipulate the core and contributed forms. Using this technique, new elements can be added, default values can be changed, or elements can even be hidden from view to simplify the user experience.
The altering of a form does not happen in a custom class; this is a hook defined in the module file. In this recipe, we will use the hook_form_FORM_ID_alter()
hook to add a telephone field to the site's configuration form.
Getting ready
This recipe assumes that you have a custom module to add the code to.
How to do it...
- In the
modules
folder of your Drupal site, create a folder namedmymodule
.
- In the
mymodule
folder, create amymodule.info.yml
, containing the following code:
name: My module description: Custom module that uses a form alter type: module core: 8.x
- Next, create a
mymodule.module
file in your module's directory:
<?php /** ...