hook_form_BASE_FORM_ID_alter

hook_form_BASE_FORM_ID_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)

Provide a form-specific alteration for shared ('base') forms.

Implementations are responsible for adding cache contexts/tags/max-age as needed. See https://www.drupal.org/developing/api/8/cache.

By default, when \Drupal::formBuilder()->getForm() is called, Drupal looks for a function with the same name as the form ID, and uses that function to build the form. In contrast, base forms allow multiple form IDs to be mapped to a single base (also called 'factory') form function.

Modules can implement hook_form_BASE_FORM_ID_alter() to modify a specific base form, rather than implementing hook_form_alter() and checking for conditions that would identify the shared form constructor.

To identify the base form ID for a particular form (or to determine whether one exists) check the $form_state. The base form ID is stored under $form_state->getBuildInfo()['base_form_id'].

Form alter hooks are called in the following order: hook_form_alter(), hook_form_BASE_FORM_ID_alter(), hook_form_FORM_ID_alter(). See hook_form_alter() for more details.

Parameters

$form: Nested array of form elements that comprise the form.

$form_state: The current state of the form.

$form_id: String representing the name of the form itself. Typically this is the name of the function that generated the form.

See also

hook_form_alter()

hook_form_FORM_ID_alter()

\Drupal\Core\Form\FormBuilderInterface::prepareForm()

Related topics

Form generation
Describes how to generate and manipulate forms and process form submissions.
Hooks
Define functions that alter the behavior of Drupal core.

File

core/lib/Drupal/Core/Form/form.api.php, line 295
Callbacks and hooks related to form system.

Code

function hook_form_BASE_FORM_ID_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  // Modification for the form with the given BASE_FORM_ID goes here. For
  // example, if BASE_FORM_ID is "node_form", this code would run on every
  // node form, regardless of node type.

  // Add a checkbox to the node form about agreeing to terms of use.
  $form['terms_of_use'] = array(
    '#type' => 'checkbox',
    '#title' => t("I agree with the website's terms and conditions."),
    '#required' => TRUE,
  );
}
doc_Drupal
2016-10-29 09:18:14
Comments
Leave a Comment

Please login to continue.