0

Can anyone please suggest how to validate the custom element option values ( select). This validate should work, once we add new element to the form and fill the option value and then click save / save and add element.

2
  • HI sorry I don't quite understand are you trying to validate a custom select option when you fill out the form or in the backend when building the form its self ?
    – taggartJ
    Apr 15, 2021 at 4:47
  • Hi @taggartJ, Here is the scenario, Editors use to create the new forms and when they include my custom select element in the form, they have to enter the option 1, option 2, etc.. for the select element. In that case i want to validate the option values they enter when they click save / save and add element button.
    – Mamallan
    Apr 15, 2021 at 5:49

1 Answer 1

0

due to explaining in comment i am thinking you are making a custom Plugin\WebformElement;

aka namespace Drupal\YOURMODULE\Plugin\WebformElement; use Drupal\webform\Plugin\WebformElementBase; ... if this is the case look at this example ( '#element_validate' => [[get_class($this), 'validateOptions']] )

 public function form(array $form, FormStateInterface $form_state) {
  $form = parent::form($form, $form_state);
  $form['general']['mycustom'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('mycustom Settings'),
  ];


  $form['general']['mycustom']['some_question_text'] = [
    '#type' => 'textfield',
    '#title' => $this->t('Some Question title '),
    '#required' => TRUE,
    '#default_value' => $this->getDefaultProperty('hello'),
    '#element_validate' => [[get_class($this), 'validateOptions']], //HERE <----
  ];

........ later on in the same class ... .......

 /**
  * Example validate 
  */
 public static function validateOptions(array &$element, FormStateInterface $form_state) {
   $name = $element['#name'];
   // EG ... $options = $element['#options']
   $form_state->setErrorByName($name, t('@m', ['@m' => 'HELLO']));
 }
2
  • Thanks for the response. I will try this and i hope this will validate will apply while we adding the element to the form(i.e select element with options key value pair), not on while end user select /fill the form and submit.
    – Mamallan
    Apr 19, 2021 at 13:17
  • @Mamallan how did it go ?
    – taggartJ
    Apr 26, 2021 at 3:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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