I build a form with the webform module and hooked it to be able to submit it via AJAX:
function mytheme_form_alter(&$form, FormStateInterface $form_state, $form_id)
{
if ( isset($form['#webform_id']) && $form['#webform_id'] == 'myform' )
{
// add an AJAX callback to the form submission
$form['actions']['submit']['#ajax'] = array(
'callback' => '\Drupal\mymodule\Controller\DefaultController::submitMyForm',
'event' => 'click',
);
}
}
Now i'd like to prevent the form submission in the submitMyForm-function when a certain condition takes place. How can I achieve that?
And how can I submit it when the condition doesn't take place?
EDIT
This worked:
function submitMyForm(&$form, FormStateInterface $form_state, $form_id)
{
if ( $condition ) {
$form_state->setErrorByName('field_name', t('error message'));
}
}