Categories
CMS Drupal Mastering Development

$form_state=>setErrorByName/setError on fieldset/container/etc

I have written a custom validation handler for webform that compares two fields. If the fields are in a container/fieldset/etc., I would like to set the error on the container instead of on the fields (since either of the two fields could be the erroneous field). For example, the fieldset is trip-dates, the fields are start-date and end-date and I want an error if start-date is after end-date.

I can use setErrorByName/setError to set errors on individual fields, but it doesn’t work if I try to set an error on the fieldset. When called against a fieldset, setErrorByName/setError call sets the error message at the top of the form, but does nothing to highlight/set an error class on the fieldset.

Webform Source:

event_details:
  '#type': fieldset
  '#title': 'Event Details'
  '#attributes':
     name: event-details
  date_container:
    '#type': fieldset
    '#title': 'Travel Dates'
    '#required': true
    '#attributes':
       name: date-container
     departure_date:
       '#type': date
       '#title': 'Departure Date'
       '#required': true
       '#default_value': '+1 day'
       '#format': short
       '#date_date_min': today
       '#datepicker': true
       '#datepicker_button': true
       '#date_date_format': m/d/Y
     return_date:
       '#type': date
       '#title': 'Return Date'
       '#required': true
       '#default_value': '+1 day'
       '#format': short
       '#date_date_min': today
       '#datepicker': true
       '#datepicker_button': true
       '#date_date_format': m/d/Y

Class Code:

  $errorFields=[
     'date_container',  //sets message, fails to highlight
     'date-container',  //sets message, fails to highlight
     'event_details][date_container',   //sets message, fails to highlight
     'event-details][date-container',   //sets message, fails to highlight
     'return-date',     //sets message, fails to highlight, as expected
     'departure-date',  //sets message, fails to highlight, as expected
     'return_date',     //sets message, highlights single field as expected
     'departure_date',  //sets message, highlights single field as expected
  ];
  foreach($errorsField as $errorField){
    if (!($left_val <= $right_val)) {
      $formState->setErrorByName(
       $errorField,
      $this->t('some weird message'));
    }
  }

I have also tried changing the names of the containers to underscores instead of dashes…no luck. If it would just add an error class to the fieldset, I could style it easily enough, but it doesn’t seem to change anything about the fieldset.

I have also tried container, details and section instead of fieldset.

Leave an answer

Your email address will not be published. Required fields are marked *