Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 37 ยท Modules and Hooks

The Form API

Build forms in Drupal with the Form API: form arrays, buildForm, validateForm, submitForm, ConfigFormBase settings forms, form state, AJAX and a runnable validation stand-in.

Every form in Drupal, from the login box to the node editor, is built with the Form API. Instead of writing HTML, you return a PHP array describing the elements. Drupal renders the HTML, adds a CSRF token and form ID, handles submission, runs validation, and gives you a place to save the result. The same array can be altered by other modules, which is why forms in Drupal are so extensible.

The PHP is read-only here (Drupal cannot run on this site). The TryIt stand-ins reproduce the build, validate and submit steps in JavaScript.

The three-step lifecycle

A form class implements three methods:

  1. buildForm() returns the form array.
  2. validateForm() checks the submitted values and sets errors.
  3. submitForm() runs only if validation passed, and does the work.
PHP
<?php

namespace Drupal\tutorial_notes\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class NoteForm extends FormBase {

  public function getFormId(): string {
    return 'tutorial_notes_note_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state): array {
    $form['title'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Title'),
      '#required' => TRUE,
      '#maxlength' => 80,
    ];
    $form['priority'] = [
      '#type' => 'select',
      '#title' => $this->t('Priority'),
      '#options' => ['low' => $this->t('Low'), 'high' => $this->t('High')],
      '#default_value' => 'low',
    ];
    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Save note'),
    ];
    return $form;
  }

  public function validateForm(array &$form, FormStateInterface $form_state): void {
    if (str_contains(strtolower($form_state->getValue('title')), 'todo')) {
      $form_state->setErrorByName('title', $this->t('Please write a real title.'));
    }
  }

  public function submitForm(array &$form, FormStateInterface $form_state): void {
    $this->messenger()->addStatus($this->t('Saved @title.', ['@title' => $form_state->getValue('title')]));
    $form_state->setRedirect('tutorial_notes.overview');
  }

}

Show the form on a page with a route whose default is _form: '\Drupal\tutorial_notes\Form\NoteForm' (instead of _controller), or embed it with \Drupal::formBuilder()->getForm(NoteForm::class).

Node.js Stand-in: build, validate, submit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice that the select check rejects hacker: Drupal does the same automatically for select and radio elements, so a tampered request cannot submit a value you never offered.

Common element types

textfield, textarea, number, email, url, tel, password, select, radios, checkboxes, checkbox, date, datetime, hidden, value (never sent to the browser), markup, details, fieldset, managed_file, entity_autocomplete, submit, actions. Useful properties: #title, #description, #default_value, #required, #attributes, #states (client-side show/hide), #access, #weight, #ajax, #element_validate.

Config forms

Settings pages extend ConfigFormBase and save into configuration:

PHP
use Drupal\Core\Form\ConfigFormBase;

class NoteSettingsForm extends ConfigFormBase {

  protected function getEditableConfigNames(): array {
    return ['tutorial_notes.settings'];
  }

  public function getFormId(): string {
    return 'tutorial_notes_settings';
  }

  public function buildForm(array $form, FormStateInterface $form_state): array {
    $config = $this->config('tutorial_notes.settings');
    $form['per_page'] = [
      '#type' => 'number',
      '#title' => $this->t('Notes per page'),
      '#default_value' => $config->get('per_page'),
      '#min' => 1,
    ];
    return parent::buildForm($form, $form_state);
  }

  public function submitForm(array &$form, FormStateInterface $form_state): void {
    $this->config('tutorial_notes.settings')
      ->set('per_page', (int) $form_state->getValue('per_page'))
      ->save();
    parent::submitForm($form, $form_state);
  }

}

Provide defaults in config/install/tutorial_notes.settings.yml (per_page: 10) and a schema in config/schema/tutorial_notes.schema.yml. The values then export and import with the site's configuration.

AJAX in forms

Add #ajax to an element and Drupal calls your callback when it changes, replacing a wrapper in the page:

PHP
$form['category'] = [
  '#type' => 'select',
  '#title' => $this->t('Category'),
  '#options' => $categories,
  '#ajax' => ['callback' => '::updateTags', 'wrapper' => 'tags-wrapper'],
];
$form['tags'] = ['#type' => 'select', '#prefix' => '<div id="tags-wrapper">', '#suffix' => '</div>', '#options' => $this->tagsFor($form_state->getValue('category'))];

public function updateTags(array &$form, FormStateInterface $form_state) {
  return $form['tags'];
}

The form rebuilds on the server with the new state, which is why you read values from $form_state inside buildForm().

Altering other forms

You can change any form with hook_form_alter (hooks). Add elements, change defaults, hide fields with #access, add validators to $form['#validate'] or submit handlers to $form['actions']['submit']['#submit'].

Security built in

  • A hidden form_token ties a form to the session and blocks cross-site request forgery for logged-in users.
  • Values come from $form_state->getValue(), already checked against the element definitions.
  • Output of #markup is filtered. Use Xss::filter() or Html::escape() if you build strings yourself, and #plain_text for text that must not contain markup.
  • Use $form_state->cleanValues() before storing everything so tokens do not get saved.
Node.js Stand-in: reject a tampered select value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which method runs only if validation succeeds?

    submitForm is skipped when any error is set during validation.
  2. 2. Which base class is used for module settings pages stored in configuration?

    ConfigFormBase wires up saving to editable config objects.
  3. 3. How do you report an error on a field?

    setErrorByName marks the element and stops submission.
  4. 4. What does the form token protect against?

    The token proves the form was issued to the current session.

Summary

  • A form is an array built in buildForm(), checked in validateForm() and handled in submitForm().
  • ConfigFormBase makes settings forms that save to configuration.
  • #ajax, #states and hook_form_alter give dynamic behaviour and extensibility.
  • Drupal validates select values and adds CSRF tokens for you.
  • Read values from $form_state, never directly from $_POST.

Next: Roles and Permissions