Form API

Drupal has an API for creating and modifying forms so all modules can specify and customize them in the same way.

Form Alter Hook

To modify an existing form, implement a form alter hook in a custom module.

In your MODULE.module file, create a function MODULE_form_alter(&$form, $form_state, $form_id) { }.

You can change the form array here, for example to add a field, change help text, or attach CSS.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21f…

You can also use MODULE_form_FORM_ID_alter(&$form, $form_state, $form_id) { }.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21f…

Custom forms

You can create a custom form and set it up to do whatever you want.

To do this, create a class in the /Drupal/MODULE/Plugin/Form namespace that extends FormBase.

The most important functions to put in are getFormId() to identify the form, buildForm() to define fields, and submitForm() to process submissions.

See UserPasswordResetForm for an example.

You will also need to specify a route to access the form.

Here is the route for the password reset form:

user.pass:
  path: '/user/password'
  defaults:
    _form: '\Drupal\user\Form\UserPasswordForm'
    _title: 'Reset your password'
  requirements:
    _access: 'TRUE'
  options:
    _maintenance_access: TRUE

Try generating a form in your custom module using drush.

Validation and Submission

validateForm() and submitForm() are used to validate and submit. These often will save values or trigger actions, show a message, and then redirect the form.

To add a validation function to an existing form
$form['#validate'][] = 'my_validation_function';

Mark a field value as invalid
$form_state->setErrorByName('field_my_field', $message);

FormElement

This abstract class extends RenderElement to provide a base for form elements to be used in a render array.

FormElements can have their own process, validate, submit functions and more.
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%2…

Tags
Form API