FormBuilder
class FormBuilder implements FormBuilderInterface, FormValidatorInterface, FormSubmitterInterface, FormCacheInterface, TrustedCallbackInterface (View source)
Provides form building and processing.
Properties
| protected ModuleHandlerInterface | $moduleHandler | The module handler. |
|
| protected EventDispatcherInterface | $eventDispatcher | The event dispatcher. |
|
| protected RequestStack | $requestStack | The request stack. |
|
| protected ElementInfoManagerInterface | $elementInfo | The element info manager. |
|
| protected CsrfTokenGenerator | $csrfToken | The CSRF token generator to validate the form token. |
|
| protected ClassResolverInterface | $classResolver | The class resolver. |
|
| protected AccountInterface | $currentUser | The current user. |
|
| protected ThemeManagerInterface | $themeManager | The theme manager. |
|
| protected FormValidatorInterface | $formValidator | The form validator. |
|
| protected FormSubmitterInterface | $formSubmitter | The form submitter. |
|
| protected FormCacheInterface | $formCache | The form cache. |
|
| protected array | $safeCoreValueCallables | Defines element value callables which are safe to run even when the form state has an invalid CSRF token. |
Methods
Constructs a new FormBuilder.
Determines the ID of a form.
Builds and processes a form for a given form ID.
Constructs a new $form from the information in $form_state.
Stores a form in the cache.
Deletes a form in the cache.
Retrieves, populates, and processes a form.
Retrieves the structured array that defines a given form.
Processes a form submission.
Renders a form action URL. It's a #lazy_builder callback.
Renders the form CSRF token. It's a #lazy_builder callback.
Prepares a structured form array.
Builds the $form['#action'].
Sets a form_token error on the given form state.
Validates user-submitted form data in the $form_state.
Redirects the user to a URL after a form has been processed.
Executes custom validation handlers for a given form.
Executes custom submission handlers for a given form.
Handles the submitted form, executing callbacks and processing responses.
Builds and processes all elements in the structured form array.
Helper function to normalize the different callable formats.
Adds the #name and #value properties of an input element before rendering.
Detects if an element triggered the form submission via Ajax.
Determines if a given button triggered the form submission.
Wraps file_upload_max_size().
Gets the current active user.
Lists the trusted callbacks provided by the implementing class.
Details
__construct(FormValidatorInterface $form_validator, FormSubmitterInterface $form_submitter, FormCacheInterface $form_cache, ModuleHandlerInterface $module_handler, EventDispatcherInterface $event_dispatcher, RequestStack $request_stack, ClassResolverInterface $class_resolver, ElementInfoManagerInterface $element_info, ThemeManagerInterface $theme_manager, CsrfTokenGenerator $csrf_token = NULL)
Constructs a new FormBuilder.
string
getFormId(FormInterface|string $form_arg, FormStateInterface $form_state)
Determines the ID of a form.
array
getForm(FormInterface|string $form_arg)
Gets a renderable form array.
This function should be used instead of self::buildForm() when $form_state is not needed (i.e., when initially rendering the form) and is often used as a menu callback.
array
buildForm(FormInterface|string $form_arg, FormStateInterface $form_state)
Builds and processes a form for a given form ID.
The form may also be retrieved from the cache if the form was built in a previous page load. The form is then passed on for processing, validation, and submission if there is proper input.
array
rebuildForm(string $form_id, FormStateInterface $form_state, array|null $old_form = NULL)
Constructs a new $form from the information in $form_state.
This is the key function for making multi-step forms advance from step to step. It is called by self::processForm() when all user input processing, including calling validation and submission handlers, for the request is finished. If a validate or submit handler set $form_state->isRebuilding() to TRUE, and if other conditions don't preempt a rebuild from happening, then this function is called to generate a new $form, the next step in the form workflow, to be returned for rendering.
Ajax form submissions are almost always multi-step workflows, so that is one common use-case during which form rebuilding occurs.
getCache(string $form_build_id, FormStateInterface $form_state)
Fetches a form from the cache.
setCache(string $form_build_id, array $form, FormStateInterface $form_state)
Stores a form in the cache.
deleteCache(string $form_build_id)
Deletes a form in the cache.
submitForm(FormInterface|string $form_arg, FormStateInterface $form_state)
Retrieves, populates, and processes a form.
This function allows you to supply values for form elements and submit a form for processing. Compare to self::getForm(), which also builds and processes a form, but does not allow you to supply values.
There is no return value, but you can check to see if there are errors by calling $form_state->getErrors().
For example:
mixed|Response
retrieveForm(string $form_id, FormStateInterface $form_state)
Retrieves the structured array that defines a given form.
RedirectResponse|null
processForm(string $form_id, array $form, FormStateInterface $form_state)
Processes a form submission.
This function is the heart of form API. The form gets built, validated and in appropriate cases, submitted and rebuilt.
array
renderPlaceholderFormAction()
Renders a form action URL. It's a #lazy_builder callback.
array
renderFormTokenPlaceholder(string $placeholder)
Renders the form CSRF token. It's a #lazy_builder callback.
prepareForm(string $form_id, array $form, FormStateInterface $form_state)
Prepares a structured form array.
Adds required elements, executes any hook_form_alter functions, and optionally inserts a validation token to prevent tampering.
protected string
buildFormAction()
Builds the $form['#action'].
$this
setInvalidTokenError(FormStateInterface $form_state)
Sets a form_token error on the given form state.
validateForm($form_id, $form, FormStateInterface $form_state)
Validates user-submitted form data in the $form_state.
RedirectResponse|null
redirectForm(FormStateInterface $form_state)
Redirects the user to a URL after a form has been processed.
After a form is submitted and processed, normally the user should be redirected to a new destination page. This function figures out what that destination should be, based on the $form_state and the 'destination' query string in the request URL, and redirects the user there.
The result of \Drupal\Core\Form|FormStateInterface::getRedirect() determines where to redirect the user. See the possible return values listed there. If the result is FALSE, then the user will not be redirected.
Here is an example of how to set up a form to redirect to the path 'user':
executeValidateHandlers($form, FormStateInterface $form_state)
Executes custom validation handlers for a given form.
Button-specific handlers are checked first. If none exist, the function falls back to form-level handlers.
executeSubmitHandlers($form, FormStateInterface $form_state)
Executes custom submission handlers for a given form.
Button-specific handlers are checked first. If none exist, the function falls back to form-level handlers.
null|Response
doSubmitForm(array $form, FormStateInterface $form_state)
Handles the submitted form, executing callbacks and processing responses.
array
doBuildForm(string $form_id, array $element, FormStateInterface $form_state)
Builds and processes all elements in the structured form array.
Adds any required properties to each element, maps the incoming input data to the proper elements, and executes any #process handlers attached to a specific element.
This is one of the three primary functions that recursively iterates a form array. This one does it for completing the form building process. The other two are self::doValidateForm() (invoked via self::validateForm() and used to invoke validation logic for each element) and RendererInterface::render() (for rendering each element). Each of these three pipelines provides ample opportunity for modules to customize what happens. For example, during this function's life cycle, the following functions get called for each element:
- $element['#value_callback']: A callable that implements how user input is mapped to an element's #value property. This defaults to a function named 'form_type_TYPE_value' where TYPE is $element['#type'].
- $element['#process']: An array of functions called after user input has been mapped to the element's #value property. These functions can be used to dynamically add child elements: for example, for the 'date' element type, one of the functions in this array is form_process_datetime(), which adds the individual 'date', and 'time'. child elements. These functions can also be used to set additional properties or implement special logic other than adding child elements: for example, for the 'details' element type, one of the functions in this array is form_process_details(), which adds the attributes and JavaScript needed to make the details work in older browsers. The #process functions are called in preorder traversal, meaning they are called for the parent element first, then for the child elements.
- $element['#after_build']: An array of callables called after self::doBuildForm() is done with its processing of the element. These are called in postorder traversal, meaning they are called for the child elements first, then for the parent element. There are similar properties containing callback functions invoked by self::doValidateForm() and RendererInterface::render(), appropriate for those operations.
Developers are strongly encouraged to integrate the functionality needed by their form or module within one of these three pipelines, using the appropriate callback property, rather than implementing their own recursive traversal of a form array. This facilitates proper integration between multiple modules. For example, module developers are familiar with the relative order in which hook_form_alter() implementations and #process functions run. A custom traversal function that affects the building of a form is likely to not integrate with hook_form_alter() and #process in the expected way. Also, deep recursion within PHP is both slow and memory intensive, so it is best to minimize how often it's done.
As stated above, each element's #process functions are executed after its
value has been set. This enables those functions to execute conditional
logic based on the current value. However, all of self::doBuildForm() runs before self::validateForm() is called, so during #process function execution, the element's #value has not yet been validated, so any code that requires validated values must reside within a submit handler.
As a security measure, user input is used for an element's #value only if the element exists within $form, is not disabled (as per the #disabled property), and can be accessed (as per the #access property, except that forms submitted using self::submitForm() bypass #access restrictions). When user input is ignored due to #disabled and #access restrictions, the element's default value is used.
Because of the preorder traversal, where #process functions of an element run before user input for its child elements is processed, and because of the Form API security of user input processing with respect to #access and
disabled described above, this generally means that #process functions
should not use an element's (unvalidated) #value to affect the #disabled or
access of child elements. Use-cases where a developer may be tempted to
implement such conditional logic usually fall into one of two categories:
- Where user input from the current submission must affect the structure of a form, including properties like #access and #disabled that affect how the next submission needs to be processed, a multi-step workflow is needed. This is most commonly implemented with a submit handler setting persistent data within $form_state based on validated values in $form_state->getValues() and checking $form_state->isRebuilding(). The form building functions must then be implemented to use the $form_state to rebuild the form with the structure appropriate for the new state.
- Where user input must affect the rendering of the form without affecting
its structure, the necessary conditional rendering logic should reside
within functions that run during the rendering phase (#pre_render,
theme, #theme_wrappers, and #post_render).
protected bool
valueCallableIsSafe(callable $value_callable)
Helper function to normalize the different callable formats.
protected
handleInputElement($form_id, $element, FormStateInterface $form_state)
Adds the #name and #value properties of an input element before rendering.
protected
elementTriggeredScriptedSubmission($element, FormStateInterface $form_state)
Detects if an element triggered the form submission via Ajax.
This detects button or non-button controls that trigger a form submission via Ajax or some other scriptable environment. These environments can set the special input key '_triggering_element_name' to identify the triggering element. If the name alone doesn't identify the element uniquely, the input key '_triggering_element_value' may also be set to require a match on element value. An example where this is needed is if there are several // buttons all named 'op', and only differing in their value.
protected
buttonWasClicked($element, FormStateInterface $form_state)
Determines if a given button triggered the form submission.
This detects button controls that trigger a form submission by being clicked and having the click processed by the browser rather than being captured by JavaScript. Essentially, it detects if the button's name and value are part of the POST data, but with extra code to deal with the convoluted way in which browsers submit data for image button clicks.
This does not detect button clicks processed by Ajax (that is done in self::elementTriggeredScriptedSubmission()) and it does not detect form submissions from Internet Explorer in response to an ENTER key pressed in a textfield (self::doBuildForm() has extra code for that).
Because this function contains only part of the logic needed to determine $form_state->getTriggeringElement(), it should not be called from anywhere other than within the Form API. Form validation and submit handlers needing to know which button was clicked should get that information from $form_state->getTriggeringElement().
protected string
getFileUploadMaxSize()
Wraps file_upload_max_size().
protected AccountInterface
currentUser()
Gets the current active user.
static string[]
trustedCallbacks()
Lists the trusted callbacks provided by the implementing class.
Trusted callbacks are public methods on the implementing class and can be invoked via \Drupal\Core\Security\DoTrustedCallbackTrait::doTrustedCallback().