function FormState::setErrorByName

Same name in other branches
  1. 9 core/lib/Drupal/Core/Form/FormState.php \Drupal\Core\Form\FormState::setErrorByName()
  2. 10 core/lib/Drupal/Core/Form/FormState.php \Drupal\Core\Form\FormState::setErrorByName()
  3. 11.x core/lib/Drupal/Core/Form/FormState.php \Drupal\Core\Form\FormState::setErrorByName()

Overrides FormStateInterface::setErrorByName

1 call to FormState::setErrorByName()
FormState::setError in core/lib/Drupal/Core/Form/FormState.php
Flags an element as having an error.

File

core/lib/Drupal/Core/Form/FormState.php, line 1055

Class

FormState
Stores information about the state of a form.

Namespace

Drupal\Core\Form

Code

public function setErrorByName($name, $message = '') {
    if ($this->isValidationComplete()) {
        throw new \LogicException('Form errors cannot be set after form validation has finished.');
    }
    $errors = $this->getErrors();
    if (!isset($errors[$name])) {
        $record = TRUE;
        $limit_validation_errors = $this->getLimitValidationErrors();
        if ($limit_validation_errors !== NULL) {
            $record = FALSE;
            foreach ($limit_validation_errors as $section) {
                // Exploding by '][' reconstructs the element's #parents. If the
                // reconstructed #parents begin with the same keys as the specified
                // section, then the element's values are within the part of
                // $form_state->getValues() that the clicked button requires to be
                // valid, so errors for this element must be recorded. As the exploded
                // array will all be strings, we need to cast every value of the
                // section array to string.
                if (array_slice(explode('][', $name), 0, count($section)) === array_map('strval', $section)) {
                    $record = TRUE;
                    break;
                }
            }
        }
        if ($record) {
            $errors[$name] = $message;
            $this->errors = $errors;
            static::setAnyErrors();
        }
    }
    return $this;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.