public function FormState::cleanValues in Drupal 9
Same name and namespace in other branches
- 8 core/lib/Drupal/Core/Form/FormState.php \Drupal\Core\Form\FormState::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
Return value
$this
Overrides FormStateInterface::cleanValues
File
- core/
lib/ Drupal/ Core/ Form/ FormState.php, line 1196
Class
- FormState
- Stores information about the state of a form.
Namespace
Drupal\Core\FormCode
public function cleanValues() {
foreach ($this
->getCleanValueKeys() as $value) {
$this
->unsetValue($value);
}
// Remove button values.
// \Drupal::formBuilder()->doBuildForm() collects all button elements in a
// form. We remove the button value separately for each button element.
foreach ($this
->getButtons() as $button) {
// Remove this button's value from the submitted form values by finding
// the value corresponding to this button.
// We iterate over the #parents of this button and move a reference to
// each parent in self::getValues(). For example, if #parents is:
// @code
// array('foo', 'bar', 'baz')
// @endcode
// then the corresponding self::getValues() part will look like this:
// @code
// array(
// 'foo' => array(
// 'bar' => array(
// 'baz' => 'button_value',
// ),
// ),
// )
// @endcode
// We start by (re)moving 'baz' to $last_parent, so we are able unset it
// at the end of the iteration. Initially, $values will contain a
// reference to self::getValues(), but in the iteration we move the
// reference to self::getValue('foo'), and finally to
// self::getValue(array('foo', 'bar')), which is the level where we
// can unset 'baz' (that is stored in $last_parent).
$parents = $button['#parents'];
$last_parent = array_pop($parents);
$key_exists = NULL;
$values =& NestedArray::getValue($this
->getValues(), $parents, $key_exists);
if ($key_exists && is_array($values)) {
unset($values[$last_parent]);
}
}
return $this;
}