I am using $form_state->setErrorByName() on a Webform element. Functionally everything works:
– The validation error is shown at the top of the page
– The specific element is marked as invalid
– The error message is displayed correctly
However, my dblog consistently reports a warning coming from FormState::getError():
foreach() argument must be of type array|object, null given
After investigating the implementation of getError(), I found that the problem occurs when $element['#parents'] is missing or NULL, which is common for Webform elements that do not have full Form API parent structures.
I tested a minimal defensive fix that prevents the warning in
/public_html/core/lib/Drupal/Core/Form/FormState.php:
public function getError(array $element) {
if ($errors = $this->getErrors()) {
$parents = [];
+ $element_parents = $element['#parents'] ?? []; // <- Indsat af CBM 2026-09-11
- foreach ($element['#parents'] as $parent) {
+ foreach ($element_parents as $parent) {
$parents[] = $parent;
$key = implode('][', $parents);
if (isset($errors[$key])) {
return $errors[$key];
}
}
}
}
This small change eliminates the dblog warning and allows setErrorByName() to work normally with Webform elements that do not provide a full #parents structure.
Would there be any problems or side effects if this defensive check were added to Drupal core?
Comments
Comment #2
uv516 commentedComment #3
cilefen commentedAs written, this seems to be a bug. Can we get the specific steps to reproduce this bug added to the issue summary?
Comment #4
cilefen commentedIn these prior cases, the fixes were to the Webform module, so maybe only certain elements are affected.
Comment #5
uv516 commentedI have created a Webform and I am using hook_form_alter() to attach a custom validator:
$form['#validate'][] = '_webform_validate';Inside _webform_validate(), I retrieve the submission entity using:
$submission = $form_state->getFormObject()->getEntity();I then fetch a specific Webform element value:
$test = $submission->getElementData('myfield') ?? [];The value is validated, and if an error is detected, I call:
$form_state->setErrorByName('myfield', $message);Everything appears to work correctly:
he link from the top error message scrolls correctly to the field
However, dblog consistently reports warnings coming from FormState::getError(), as described earlier.
The form behaves correctly, but the repeated foreach() warnings indicate that getError() is not handling Webform elements that lack a full Form API #parents structure.