Score:1

Set error message only on errornous field(s) when validating multiple instances of the same field

ne flag
  • I have a form where the users can add one or more "units".
  • I want to validate and return an error message on the problematic field when the unit does not have a value "leader"
  • With the below code, an error message appears under all unit fields even if some inputs do not have error.

How can I add the error message only to the problematic field? Here's my attempt so far.


    // Foreach $values['unit'], check if this field has the key
    // "leader". If not, add an error message and require the user
    // to select a sub field which has area leaders.
    if ($values['unit']) {
      foreach ($values['unit'] as $unit) {
        if (empty($unit["leader"])) {
          $form_state->setErrorByName('unit',
            new TranslatableMarkup('Please select a unit with a leader.'));
          break;
        }
      }
    }

Jaypan avatar
de flag
Is this an a form validation handler or an element validation handler or somewhere else?
Score:2
de flag

Assuming the code is a form validation handler, you should be able to do something like this:

if ($values['unit']) {
  foreach ($values['unit'] as $index => $unit) {
    if (empty($unit['leader'])) {
      $form_state->setError($form['unit']['widget'][$index],t('Please select a unit with a leader.'));
    }
  }
}

However, if the unit element of the form is a child of a tree, then the first argument to setError() must be updated to the actual location of the element within the $form array.

John Doe avatar
ne flag
Thank you so much for pointing me to `setError`! I notice that the $values array has an item "add more", which holds information for the "add more" button. After adding `array_pop($units);` to remove this "add more" array, your code works. Really appreciate your time!
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.