FormState
class FormState implements FormStateInterface (View source)
Stores information about the state of a form.
Traits
Provides methods to manage form state values.
Properties
| static protected bool | $anyErrors | Tracks if any errors have been set on any form. |
|
| protected array | $complete_form | The complete form structure. |
|
| protected array | $build_info | An associative array of information stored by Form API that is necessary to build and rebuild the form from cache when the original context may no longer be available:
|
|
| protected array | $rebuild_info | Similar to self::$build_info, but pertaining to \Drupal\Core\Form\FormBuilderInterface::rebuildForm(). |
|
| protected bool | $rebuild | Normally, after the entire form processing is completed and submit handlers have run, a form is considered to be done and \Drupal\Core\Form\FormSubmitterInterface::redirectForm() will redirect the user to a new page using a GET request (so a browser refresh does not re-submit the form). However, if 'rebuild' has been set to TRUE, then a new copy of the form is immediately built and sent to the browser, instead of a redirect. This is used for multi-step forms, such as wizards and confirmation forms. Normally, self::$rebuild is set by a submit handler, since it is usually logic within a submit handler that determines whether a form is done or requires another step. However, a validation handler may already set self::$rebuild to cause the form processing to bypass submit handlers and rebuild the form instead, even if there are no validation errors. |
|
| protected bool | $invalidToken | If set to TRUE the form will skip calling form element value callbacks, except for a select list of callbacks provided by Drupal core that are known to be safe. |
|
| protected Response|null | $response | Used when a form needs to return some kind of a \Symfony\Component\HttpFoundation\Response object, e.g., a \Symfony\Component\HttpFoundation\BinaryFileResponse when triggering a file download. If you use self::setRedirect() or self::setRedirectUrl(), it will be used to build a \Symfony\Component\HttpFoundation\RedirectResponse and will populate this key. |
|
| protected Url|RedirectResponse|null | $redirect | Used to redirect the form on submission. |
|
| protected bool | $no_redirect | If set to TRUE the form will NOT perform a redirect, even if self::$redirect is set. |
|
| protected string | $method | The HTTP form method to use for finding the input for this form. |
|
| protected string | $requestMethod | The HTTP method used by the request building or processing this form. |
|
| protected bool | $cache | If set to TRUE the original, unprocessed form structure will be cached, which allows the entire form to be rebuilt from cache. A typical form workflow involves two page requests; first, a form is built and rendered for the user to fill in. Then, the user fills the form in and submits it, triggering a second page request in which the form must be built and processed. By default, $form and $form_state are built from scratch during each of these page requests. Often, it is necessary or desired to persist the $form and $form_state variables from the initial page request to the one that processes the submission. 'cache' can be set to TRUE to do this. |
|
| protected bool | $no_cache | If set to TRUE the form will NOT be cached, even if 'cache' is set. |
|
| protected array | $values | An associative array of values submitted to the form. |
|
| protected array | $cleanValueKeys | An associative array of form value keys to be removed by cleanValues(). |
|
| protected array|null | $input | The array of values as they were submitted by the user. |
|
| protected bool | $always_process | If TRUE and the method is GET, a form_id is not necessary. |
|
| protected bool | $must_validate | Ordinarily, a form is only validated once, but there are times when a form is resubmitted internally and should be validated again. Setting this to TRUE will force that to happen. This is most likely to occur during Ajax operations. |
|
| protected bool | $programmed | If TRUE, the form was submitted programmatically, usually invoked via \Drupal\Core\Form\FormBuilderInterface::submitForm(). Defaults to FALSE. |
|
| protected bool | $programmed_bypass_access_check | If TRUE, programmatic form submissions are processed without taking #access into account. Set this to FALSE when submitting a form programmatically with values that may have been input by the user executing the current request; this will cause #access to be respected as it would on a normal form submission. Defaults to TRUE. |
|
| protected bool | $process_input | TRUE signifies correct form submission. This is always TRUE for programmed forms coming from \Drupal\Core\Form\FormBuilderInterface::submitForm() (see 'programmed' key), or if the form_id coming from the \Drupal::request()->request data is set and matches the current form_id. |
|
| protected bool | $submitted | If TRUE, the form has been submitted. Defaults to FALSE. |
|
| protected bool | $executed | If TRUE, the form was submitted and has been processed and executed. |
|
| protected array|null | $triggering_element | The form element that triggered submission, which may or may not be a button (in the case of Ajax forms). This key is often used to distinguish between various buttons in a submit handler, and is also used in Ajax handlers. |
|
| protected bool | $has_file_element | If TRUE, there is a file element and Form API will set the appropriate 'enctype' HTML attribute on the form. |
|
| protected array | $groups | Contains references to details elements to render them within vertical tabs. |
|
| protected array | $storage | This is not a special key, and no specific support is provided for it in the Form API. By tradition it was the location where application-specific data was stored for communication between the submit, validation, and form builder functions, especially in a multi-step-style form. Form implementations may use any key(s) within $form_state (other than the keys listed here and other reserved ones used by Form API internals) for this kind of storage. The recommended way to ensure that the chosen key doesn't conflict with ones used by the Form API or other modules is to use the module name as the key name or a prefix for the key name. For example, the entity form classes use $this->entity in entity forms, or $form_state->getFormObject()->getEntity() outside the controller, to store information about the entity being edited, and this information stays available across successive clicks of the "Preview" button (if available) as well as when the "Save" button is finally clicked. |
|
| protected array | $buttons | A list containing copies of all submit and button elements in the form. |
|
| protected array | $temporary | Holds temporary data accessible during the current page request only. |
|
| protected bool | $validation_complete | Tracks if the form has finished validation. |
|
| protected array | $errors | Contains errors for this form. |
|
| protected array|null | $limit_validation_errors | Stores which errors should be limited during validation. |
|
| protected array | $validate_handlers | Stores the gathered validation handlers. |
|
| protected array | $submit_handlers | Stores the gathered submission handlers. |
Methods
Returns the submitted and sanitized form values.
Implements \Drupal\Core\Form\FormStateInterface::getValue()
Implements \Drupal\Core\Form\FormStateInterface::setValues()
Implements \Drupal\Core\Form\FormStateInterface::setValue()
Implements \Drupal\Core\Form\FormStateInterface::unsetValue()
Implements \Drupal\Core\Form\FormStateInterface::hasValue()
Implements \Drupal\Core\Form\FormStateInterface::isValueEmpty()
Implements \Drupal\Core\Form\FormStateInterface::setValueForElement()
Sets the value of the form state.
Sets this form to always be processed.
Determines if this form should always be processed.
Stores the submit and button elements for the form.
Returns the submit and button elements for the form.
Sets this form to be cached.
Determines if the form should be cached.
Prevents the form from being cached.
Sets that the form was submitted and has been processed and executed.
Determines if the form was submitted and has been processed and executed.
Sets references to details elements to render them within vertical tabs.
Returns references to details elements to render them within vertical tabs.
Sets that this form has a file element.
Returns whether this form has a file element.
Sets the limited validation error sections.
Retrieves the limited validation error sections.
Sets the HTTP method to use for the form's submission.
Returns the HTTP form method.
Sets the HTTP method used by the request that is building the form.
Checks whether the request method is a "safe" HTTP method.
Enforces that validation is run.
Checks if validation is enforced.
Prevents the form from redirecting.
Determines if redirecting has been prevented.
Sets that the form should process input.
Determines if the form input will be processed.
Sets that this form was submitted programmatically.
Returns if this form was submitted programmatically.
Sets if this form submission should bypass #access.
Determines if this form submission should bypass #access.
Sets the rebuild info.
Gets the rebuild info.
Adds a value to the rebuild info.
Sets the entire set of arbitrary data.
Returns the entire set of arbitrary data.
Sets the submit handlers.
Gets the submit handlers.
Sets that the form has been submitted.
Determines if the form has been submitted.
Sets temporary data.
Gets temporary data.
Gets an arbitrary value from temporary storage.
Sets an arbitrary value in temporary storage.
Determines if a temporary value is present.
Sets the form element that triggered submission.
Gets the form element that triggered submission.
Sets the validate handlers.
Gets the validate handlers.
Sets that validation has been completed.
Determines if validation has been completed.
Ensures an include file is loaded whenever the form is processed.
Returns an array representation of the cacheable portion of the form state.
Stores the complete form array.
Returns a reference to the complete form array.
Gets any arbitrary property.
Sets a value to an arbitrary property.
Determines if an arbitrary property is present.
Sets the build info for the form.
Returns the build info for the form.
Adds a value to the build info.
Returns the form values as they were submitted by the user.
Sets the form values as though they were submitted by a user.
Sets a response for this form.
Gets a response for this form.
Sets the redirect for the form.
Gets the value to use for redirecting after the form has been executed.
Sets the global status of errors.
Determines if any forms have any errors.
Files an error against a form element.
Flags an element as having an error.
Clears all errors against all form elements made by self::setErrorByName().
Returns the error message filed against the given form element.
Returns an associative array of all errors.
Sets the form to be rebuilt after processing.
Determines if the form should be rebuilt after processing.
Converts support notations for a form callback to a valid callable.
Sets the form object that is responsible for building this form.
Returns the form object that is responsible for building this form.
Gets the keys of the form values that will be cleaned.
Sets the keys of the form values that will be cleaned.
Adds a key to the array of form values that will be cleaned.
Removes internal Form API elements and buttons from submitted form values.
Flags the form state as having or not an invalid token.
Determines if the form has an invalid token.
Wraps ModuleHandler::loadInclude().
Details
array
getValues()
Returns the submitted and sanitized form values.
getValue($key, $default = NULL)
Implements \Drupal\Core\Form\FormStateInterface::getValue()
setValues(array $values)
Implements \Drupal\Core\Form\FormStateInterface::setValues()
setValue($key, $value)
Implements \Drupal\Core\Form\FormStateInterface::setValue()
unsetValue($key)
Implements \Drupal\Core\Form\FormStateInterface::unsetValue()
hasValue($key)
Implements \Drupal\Core\Form\FormStateInterface::hasValue()
isValueEmpty($key)
Implements \Drupal\Core\Form\FormStateInterface::isValueEmpty()
setValueForElement(array $element, $value)
Implements \Drupal\Core\Form\FormStateInterface::setValueForElement()
$this
setFormState(array $form_state_additions)
Sets the value of the form state.
$this
setAlwaysProcess(bool $always_process = TRUE)
Sets this form to always be processed.
This should only be used on RESTful GET forms that do NOT write data, as this could lead to security issues. It is useful so that searches do not need to have a form_id in their query arguments to trigger the search.
bool
getAlwaysProcess()
Determines if this form should always be processed.
$this
setButtons(array $buttons)
Stores the submit and button elements for the form.
array
getButtons()
Returns the submit and button elements for the form.
$this
setCached(bool $cache = TRUE)
Sets this form to be cached.
bool
isCached()
Determines if the form should be cached.
$this
disableCache()
Prevents the form from being cached.
$this
setExecuted()
Sets that the form was submitted and has been processed and executed.
bool
isExecuted()
Determines if the form was submitted and has been processed and executed.
$this
setGroups(array $groups)
Sets references to details elements to render them within vertical tabs.
array
getGroups()
Returns references to details elements to render them within vertical tabs.
$this
setHasFileElement(bool $has_file_element = TRUE)
Sets that this form has a file element.
bool
hasFileElement()
Returns whether this form has a file element.
$this
setLimitValidationErrors(array|null $limit_validation_errors)
Sets the limited validation error sections.
array|null
getLimitValidationErrors()
Retrieves the limited validation error sections.
$this
setMethod(string $method)
Sets the HTTP method to use for the form's submission.
This is what the form's "method" attribute should be, not necessarily what the current request's HTTP method is. For example, a form can have a method attribute of POST, but the request that initially builds it uses GET.
bool
isMethodType(string $method_type)
Returns the HTTP form method.
$this
setRequestMethod(string $method)
Sets the HTTP method used by the request that is building the form.
protected bool
isRequestMethodSafe()
Checks whether the request method is a "safe" HTTP method.
Link below defines GET and HEAD as "safe" methods, meaning they SHOULD NOT have side-effects, such as persisting $form_state changes.
$this
setValidationEnforced(bool $must_validate = TRUE)
Enforces that validation is run.
bool
isValidationEnforced()
Checks if validation is enforced.
$this
disableRedirect(bool $no_redirect = TRUE)
Prevents the form from redirecting.
bool
isRedirectDisabled()
Determines if redirecting has been prevented.
$this
setProcessInput(bool $process_input = TRUE)
Sets that the form should process input.
bool
isProcessingInput()
Determines if the form input will be processed.
$this
setProgrammed(bool $programmed = TRUE)
Sets that this form was submitted programmatically.
bool
isProgrammed()
Returns if this form was submitted programmatically.
$this
setProgrammedBypassAccessCheck(bool $programmed_bypass_access_check = TRUE)
Sets if this form submission should bypass #access.
bool
isBypassingProgrammedAccessChecks()
Determines if this form submission should bypass #access.
$this
setRebuildInfo(array $rebuild_info)
Sets the rebuild info.
array
getRebuildInfo()
Gets the rebuild info.
$this
addRebuildInfo(string $property, mixed $value)
Adds a value to the rebuild info.
$this
setStorage(array $storage)
Sets the entire set of arbitrary data.
array
getStorage()
Returns the entire set of arbitrary data.
$this
setSubmitHandlers(array $submit_handlers)
Sets the submit handlers.
array
getSubmitHandlers()
Gets the submit handlers.
$this
setSubmitted()
Sets that the form has been submitted.
bool
isSubmitted()
Determines if the form has been submitted.
$this
setTemporary(array $temporary)
Sets temporary data.
array
getTemporary()
Gets temporary data.
mixed
getTemporaryValue(string|array $key)
Gets an arbitrary value from temporary storage.
$this
setTemporaryValue(string|array $key, mixed $value)
Sets an arbitrary value in temporary storage.
hasTemporaryValue(string $key)
Determines if a temporary value is present.
$this
setTriggeringElement(array|null $triggering_element)
Sets the form element that triggered submission.
array|null
getTriggeringElement()
Gets the form element that triggered submission.
$this
setValidateHandlers(array $validate_handlers)
Sets the validate handlers.
array
getValidateHandlers()
Gets the validate handlers.
$this
setValidationComplete(bool $validation_complete = TRUE)
Sets that validation has been completed.
bool
isValidationComplete()
Determines if validation has been completed.
string|false
loadInclude(string $module, string $type, string|null $name = NULL)
Ensures an include file is loaded whenever the form is processed.
Example:
array
getCacheableArray()
Returns an array representation of the cacheable portion of the form state.
$this
setCompleteForm(array $complete_form)
Stores the complete form array.
array
getCompleteForm()
Returns a reference to the complete form array.
mixed
get(string|array $property)
Gets any arbitrary property.
$this
set(string|array $property, mixed $value)
Sets a value to an arbitrary property.
has(string|array $property)
Determines if an arbitrary property is present.
$this
setBuildInfo(array $build_info)
Sets the build info for the form.
array
getBuildInfo()
Returns the build info for the form.
$this
addBuildInfo(string $property, mixed $value)
Adds a value to the build info.
array
getUserInput()
Returns the form values as they were submitted by the user.
These are raw and unvalidated, so should not be used without a thorough understanding of security implications. In almost all cases, code should use self::getValues() and self::getValue() exclusively.
$this
setUserInput(array $user_input)
Sets the form values as though they were submitted by a user.
$this
setResponse(Response $response)
Sets a response for this form.
If a response is set, it will be used during processing and returned directly. The form will not be rebuilt or redirected.
Response|null
getResponse()
Gets a response for this form.
If a response is set, it will be used during processing and returned directly. The form will not be rebuilt or redirected.
$this
setRedirect(string $route_name, array $route_parameters = [], array $options = [])
Sets the redirect for the form.
$this
setRedirectUrl(Url $url)
Sets the redirect URL for the form.
mixed
getRedirect()
Gets the value to use for redirecting after the form has been executed.
static protected
setAnyErrors(bool $errors = TRUE)
Sets the global status of errors.
static bool
hasAnyErrors()
Determines if any forms have any errors.
$this
setErrorByName(string $name, string $message = '')
Files an error against a form element.
When a validation error is detected, the validator calls this method to indicate which element needs to be changed and provide an error message. This causes the Form API to not execute the form submit handlers, and instead to re-display the form to the user with the corresponding elements rendered with an 'error' CSS class (shown as red by default).
The standard behavior of this method can be changed if a button provides the #limit_validation_errors property. Multistep forms not wanting to validate the whole form can set #limit_validation_errors on buttons to limit validation errors to only certain elements. For example, pressing the "Previous" button in a multistep form should not fire validation errors just because the current step has invalid values. If
limit_validation_errors is set on a clicked button, the button must also
define a #submit property (may be set to an empty array). Any #submit handlers will be executed even if there is invalid input, so extreme care should be taken with respect to any actions taken by them. This is typically not a problem with buttons like "Previous" or "Add more" that do not invoke persistent storage of the submitted form values. Do not use the
limit_validation_errors property on buttons that trigger saving of form
values to the database.
The #limit_validation_errors property is a list of "sections" within $form_state->getValues() that must contain valid values. Each "section" is an array with the ordered set of keys needed to reach that part of $form_state->getValues() (i.e., the #parents property of the element).
Example 1: Allow the "Previous" button to function, regardless of whether any user input is valid.
$this
setError(array $element, string $message = '')
Flags an element as having an error.
clearErrors()
Clears all errors against all form elements made by self::setErrorByName().
string|null
getError(array $element)
Returns the error message filed against the given form element.
Form errors higher up in the form structure override deeper errors as well as errors on the element itself.
array
getErrors()
Returns an associative array of all errors.
$this
setRebuild(bool $rebuild = TRUE)
Sets the form to be rebuilt after processing.
bool
isRebuilding()
Determines if the form should be rebuilt after processing.
array|string
prepareCallback(string|array $callback)
Converts support notations for a form callback to a valid callable.
Specifically, supports methods on the form/callback object as strings when they start with ::, for example "::submitForm()".
$this
setFormObject(FormInterface $form_object)
Sets the form object that is responsible for building this form.
FormInterface
getFormObject()
Returns the form object that is responsible for building this form.
array
getCleanValueKeys()
Gets the keys of the form values that will be cleaned.
$this
setCleanValueKeys(array $cleanValueKeys)
Sets the keys of the form values that will be cleaned.
$this
addCleanValueKey($cleanValueKey)
Adds a key to the array of form values that will be cleaned.
$this
cleanValues()
Removes internal Form API elements and buttons from submitted form values.
This function can be used when a module wants to store all submitted form values, for example, by serializing them into a single database column. In such cases, all internal Form API values and all form button elements should not be contained, and this function allows their removal before the module proceeds to storage. Next to button elements, the following internal values are removed by default.
- form_id
- form_token
- form_build_id
- op
$this
setInvalidToken(bool $invalid_token)
Flags the form state as having or not an invalid token.
bool
hasInvalidToken()
Determines if the form has an invalid token.
protected
moduleLoadInclude($module, $type, $name = NULL)
Wraps ModuleHandler::loadInclude().