0

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

1 Answer 1

2

Sitepoint has a nice example of Ajax form validation in Drupal 8:

https://www.sitepoint.com/using-ajax-forms-drupal-8/

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.