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;
}