0

I have a webform with a composite component that allows multiple rows to be added. The structure is something like this, in case that makes it clearer:

webform
  sample_details - composite component which allows multiple 'rows', containing:
    sample_ref 
    date_sampled (field I want to set the error on)

I followed 'method 2 - webform handler' on this guide. I'm able to do the validation itself and set an error on other components, but not on sub-components in the composite one.

This post addresses a similar problem, but the technique hasn't helped me.

I've tried

$form_state->setErrorByName( 'date_sampled', $this->t( 'must not have a sample date in the future.' ) );

and

$form_state->setErrorByName( 'sample_details][date_sampled]', $this->t( 'must not have a sample date in the future.' ) );

and a few other things but it seems like I'm missing something. It seems that setErrorByName can't work on sub-components because they don't have a standard #parents array? Is there a way of achieving this without having to switch to 'the old way'?

1

The element name "sample_details][date_sampled]" specified in the first parameter of setByErrorName is not correct.

It should be

// $key = your multi field array key eg 0,1,2,3 
$formState->setErrorByName('sample_details][items][' . $key . '][_item_][date_sampled', $this->t('must not have a sample date in the future.'));

You can find out the exact element name by two methods:

  1. $formState->getUserInput() will give you the exact array pattern to use for setting error by name.
  2. Inspect the element from the browser and use the value of name attribute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.