Information for: DEVELOPERS   PARTNERS

Add a field to an existing form

Fast Track to Drupal 8 Coding – Back to intro
Previous lesson - Build a new form
Next lesson – Create users programmatically

Lesson Goal

Add an Accept Terms check box to the User Registration Form.

Implementation Method

You can complete this lesson by using either hook_form_alter OR hook_form_FORM_ID_alter. Because we need to do a form-specific changes, we will use the hook_form_FORM_ID_alter.

Drupal Version Method
Drupal 7 Use hook_form_FORM_ID_alter()
Drupal 8 Use hook_form_FORM_ID_alter()

Drupal 7 method

Add the following code to the lotus.module file:

<?php
/**
* @file
* Add a field to an existing form.
*/
/**
* Implements hook_form_FORM_ID_alter().
*/
function lotus_form_user_register_form_alter(&amp;$form, &amp;$form_state, $form_id) {
  // Add a checkbox to registration form for terms.
  $form['terms'] = array(
    '#type' => 'checkbox',
    '#title' => t("I accept the website's terms."),
    '#required' => TRUE,
  );
}

Drupal 8 method

Add the following code to the lotus.module file:

<?php
/**
* @file
* Add a field to an existing form.
*/
use \Drupal\Core\Form\FormStateInterface;

/**
* Implements hook_form_FORM_ID_alter().
*/
function lotus_form_user_register_form_alter(&amp;$form, FormStateInterface $form_state, $form_id) {
  // Add a checkbox to registration form for terms.
  $form['terms'] = array(
    '#type' => 'checkbox',
    '#title' => t("I accept the website's terms."),
    '#required' => TRUE,
  );
}