How to use hook form alter to add to an existing form in Drupal 8

Modifying an existing form on a drupal 8 site

These are notes/documentation on how to change an existing form on a drupal 8 (D8) site so that you can add an element to it.  "[module]" needs to be replaced with the module name in the areas it is referenced in this document.

Create a D8 module

You need to create a drupal module with at least 2 files (with appropriate content for them to be an actual D8 module):

  1. [module].info.yml
  2. [module].module

"[module]" needs to be replaced with the module name and the files need to be setup properly to build out an actual module (this document does not discuss building a module)

Identifying the form ID of the form to be modified

Edit the [module].module file and use it to discover the form ID of the form to be modified. Add the following function:

function [module]_form_alter(&$form, &$form_state, $form_id) {
    drupal_set_message(t($form_id));
  }

Remove this function once the formID is found.

Adding a checkbox control to an existing D8 form

This function needs to be placed into the [module].module file in order for it to work and put a checkbox into the form (by form ID that was discovered earlier):

  function [module]_form_alter(&$form, &$form_state, $form_id) {
    drupal_set_message(t($form_id));

    if ($form_id == '[formID found]') {
           $form['limit_county'] = array(
             '#type' => 'checkbox',
             '#title' => t('Limit by county'),
           );
         }

  }

Need to replace "[formID found]" with the formID that was discovered earlier.

Category