0

I have a form that has radio buttons and the user needs to select at least one option. If they do, a modal window will pop-up. If they don't, I need to redisplay the form with the saved values and the message "Please select one item" in the message area. Right now, if they don't select one item nothing happens and then the message is displayed after the page is refreshed.

public function buildForm(array $form, FormStateInterface $form_state, $form_config = NULL)
{
    if (!empty($form_state->getBuildInfo()['args']['form_ajax'])) {
        $form['#attached']['library'][] = 'core/drupal.dialog.ajax';
        $form['actions']['submit']['#ajax'] = [
            'callback' => '::crmform_ajax_submit',
        ];
    }
    return $form;
}
public function validateForm(array &$form, FormStateInterface $form_state)
{
    $selected = $this->crmform_validate_element_selected($form_state, 'radio');
    if (!$selected) {
        $form_state->setErrorByName('form', t('Please select one item'));
    }
}
public function crmform_ajax_submit(&$form, FormStateInterface $form_state)
{
    $errors = $form_state->getErrors();
    $response = new AjaxResponse();
    if (!empty($errors)) {
       $form_state->setRebuild();
       return $response;
    }
    $response->addCommand(new OpenModalDialogCommand($dialog_title, $form_data, $options));
    return $response;
}
1
  • In case of an error you return an empty ajax response. You need to return the error message or the complete form which contains the error message.
    – 4uk4
    May 31, 2017 at 6:55

1 Answer 1

1

You can use contributed module Clientside Validation which is very close to your requirement.

This module adds clientside validation (aka "Ajax form validation") for all forms and webforms using jquery.validate. The included jquery.validate.js file is patched because we needed to be able to hide empty messages.

Your Answer

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

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