0

I want to add a custom validation to text input, I followed the instruction provided in https://www.drupal.org/docs/8/modules/webform/webform-cookbook/how-to-add-custom-validation-to-a-webform-element

I have a requirement which needs to verify an id entered into a text box, by making a REST API call to another system, the issue is to make that REST API call, I need another text parameter which is also inputed into the webform. I have written a custom handler which makes that rest call, but that custom handler work on webform post save option only, how can I pass more than 2 fields to the validate function mentioned in the example given.

function onboarding_webform_element_alter(array &$element, FormStateInterface $form_state, array $context) {
    // check for desired element   
   if (isset($element['#webform_id']) && $element['#webform_id'] === 'register_account--surname'){
     $surname= $element['#default_value'];
    $form_state->setValue('SOME_NAME', $surname);    
   }  
   if (isset($element['#webform_id']) && $element['#webform_id'] === 'register_account--proda_id') {

        $element['#element_validate'][] = array(
            'Drupal\dhs_vendor_onboarding\Validate\DhsValidateConstraint',
            'validate'
        );      
    } 
}

In the validate function:

public static function validate(array &$element, FormStateInterface $formState, array &$form) {
        ksm($formState->getValue('SOME_NAME'));
        $webformKey = $element['#webform_key'];       
        $value = $formState->getValue($webformKey);
        $surname= $formState->getValue('SOME_NAME');
        }

I am not getting any value for surname

1 Answer 1

0

i was able to get the value of surname from the Formstate, the form state had surname in surname field itself.

public static function validate(array &$element, FormStateInterface $formState, array &$form) {      
    $webformKey = $element['#webform_key'];       
    $value = $formState->getValue($webformKey);
    $surname= $formState->getValue('surname');
}

this did the trick.

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.