Drupal 8  8.0.2
Form generation

Data Structures

class  FormBuilder
 
class  FormCache
 
class  FormHelper
 
interface  FormInterface
 
interface  FormStateInterface
 

Functions

 drupal_get_destination ()
 
 hook_form_alter (&$form,\Drupal\Core\Form\FormStateInterface $form_state, $form_id)
 
 hook_form_FORM_ID_alter (&$form,\Drupal\Core\Form\FormStateInterface $form_state, $form_id)
 
 hook_form_BASE_FORM_ID_alter (&$form,\Drupal\Core\Form\FormStateInterface $form_state, $form_id)
 
 getAsArray ()
 

Detailed Description

Describes how to generate and manipulate forms and process form submissions.

Drupal provides a Form API in order to achieve consistency in its form processing and presentation, while simplifying code and reducing the amount of HTML that must be explicitly generated by a module.

Creating forms

Forms are defined as classes that implement the and are built using the class. Drupal provides a couple of utility classes that can be extended as a starting point for most basic forms, the most commonly used of which is . FormBuilder handles the low level processing of forms such as rendering the necessary HTML, initial processing of incoming $_POST data, and delegating to your implementation of FormInterface for validation and processing of submitted data.

Here is an example of a Form class:

namespace Drupal\mymodule\Form;
use Drupal\Core\Form\FormBase;
class ExampleForm extends FormBase {
public function getFormId() {
// Unique ID of the form.
return 'example_form';
}
public function buildForm(array $form, FormStateInterface $form_state) {
// Create a $form API array.
$form['phone_number'] = array(
'#type' => 'tel',
'#title' => $this->t('Your phone number')
);
return $form;
}
public function validateForm(array &$form, FormStateInterface $form_state) {
// Validate submitted form data.
}
public function submitForm(array &$form, FormStateInterface $form_state) {
// Handle submitted form data.
}
}

Retrieving and displaying forms

::formBuilder()->getForm() should be used to handle retrieving, processing, and displaying a rendered HTML form. Given the ExampleForm defined above, ::formBuilder()->getForm('Drupal') would return the rendered HTML of the form defined by ExampleForm::buildForm(), or call the validateForm() and submitForm(), methods depending on the current processing state.

The argument to ::formBuilder()->getForm() is the name of a class that implements FormBuilderInterface. Any additional arguments passed to the getForm() method will be passed along as additional arguments to the ExampleForm::buildForm() method.

For example:

$extra = '612-123-4567';
$form = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\ExampleForm', $extra);
...
public function buildForm(array $form, FormStateInterface $form_state, $extra = NULL)
$form['phone_number'] = array(
'#type' => 'tel',
'#title' => $this->t('Your phone number'),
'#value' => $extra,
);
return $form;
}

Alternatively, forms can be built directly via the routing system which will take care of calling ::formBuilder()->getForm(). The following example demonstrates the use of a routing.yml file to display a form at the given route.

example.form:
path: '/example-form'
defaults:
_title: 'Example form'
_form: '\Drupal\mymodule\Form\ExampleForm'

The $form argument to form-related functions is a specialized render array containing the elements and properties of the form. For more about render arrays, see the Render API topic. For more detailed explanations of the Form API workflow, see the Form API documentation section. In addition, there is a set of Form API tutorials in the Examples for Developers project.

In the form builder, validation, submission, and other form methods, $form_state is the primary influence on the processing of the form and is passed to most methods, so they can use it to communicate with the form system and each other. $form_state is an object that implements .

Function Documentation

drupal_get_destination ( )

Prepares a 'destination' URL query parameter for use with url().

Used to direct the user back to the referring page after completing a form. By default the current URL is returned. If a destination exists in the previous request, that destination is returned. As such, a destination can persist across multiple pages.

Returns
array An associative array containing the key:
  • destination: The value of the current request's 'destination' query parameter, if present. This can be either a relative or absolute URL. However, for security, redirection to external URLs is not performed. If the query parameter isn't present, then the URL of the current request is returned.
See Also
::checkRedirectUrl()
Deprecated:
in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0. Use the redirect.destination service.
getAsArray ( )

Prepares a 'destination' URL query parameter for use with .

Used to direct the user back to the referring page after completing a form. By default the current URL is returned. If a destination exists in the current request, that destination is returned. As such, a destination can persist across multiple pages.

Returns
array An associative array containing the key:
  • destination: The value of the current request's 'destination' query parameter, if present. This can be either a relative or absolute URL. However, for security, redirection to external URLs is not performed. If the query parameter isn't present, then the URL of the current request is returned.
See Also
::checkRedirectUrl()

Implemented in RedirectDestination.

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

Perform alterations before a form is rendered.

One popular use of this hook is to add form elements to the node form. When altering a node form, the node entity can be retrieved by invoking $form_state->getFormObject()->getEntity().

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

In addition to hook_form_alter(), which is called for all forms, there are two more specific form hooks available. The first, hook_form_BASE_FORM_ID_alter(), allows targeting of a form/forms via a base form (if one exists). The second, hook_form_FORM_ID_alter(), can be used to target a specific form directly.

The call order is as follows: all existing form alter functions are called for module A, then all for module B, etc., followed by all for any base theme(s), and finally for the theme itself. The module order is determined by system weight, then by module name.

Within each module, form alter hooks are called in the following order: first, hook_form_alter(); second, hook_form_BASE_FORM_ID_alter(); third, hook_form_FORM_ID_alter(). So, for each module, the more general hooks are called first followed by the more specific.

Parameters
$formNested array of form elements that comprise the form.
$form_stateThe current state of the form. The arguments that ::formBuilder()->getForm() was originally called with are available in the array $form_state->getBuildInfo()['args'].
$form_idString representing the name of the form itself. Typically this is the name of the function that generated the form.
See Also
hook_form_BASE_FORM_ID_alter()
hook_form_FORM_ID_alter()

References Drupal\config(), and t().

Here is the call graph for this function:

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 ::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
$formNested array of form elements that comprise the form.
$form_stateThe current state of the form.
$form_idString 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()
::prepareForm()

References t().

Here is the call graph for this function:

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

Provide a form-specific alteration instead of the global hook_form_alter().

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

Modules can implement hook_form_FORM_ID_alter() to modify a specific form, rather than implementing hook_form_alter() and checking the form ID, or using long switch statements to alter multiple forms.

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
$formNested array of form elements that comprise the form.
$form_stateThe current state of the form. The arguments that ::formBuilder()->getForm() was originally called with are available in the array $form_state->getBuildInfo()['args'].
$form_idString 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_BASE_FORM_ID_alter()
::prepareForm()

References t().

Here is the call graph for this function: