3

Drupal 8 comes with client-side JavaScript form validation; however, for a submit button with #ajax, it is disabled. How can I enable it?

0

1 Answer 1

5

I had the same question this morning. Here's how I got it to work.

Add an invisible button and specify the #ajax on that.

$form['actions'] = array(
  '#type' => 'actions',
  'submit' =>array(
    '#type' => 'submit',
    '#value' => 'Submit',
  ),
  'validation-hack' => array(
    '#type' => 'button',
    '#value' => 'validated',
    '#attributes' => array('style' => 'display:none'),
    '#ajax' => array(
      'callback' => array($this, 'doSomething'),
      'event' => 'click',
      'progress' => array(
        'type' => 'throbber',
        'message' => 'Example...',
      ),
    ),
  ),
);

Then add a submit handler on the form that stops the form submission and then calls click on the hidden button.

  (function($, Drupal) {
    Drupal.behaviors.example = {
      attach: function(context, settings) {
        $(context).find('#example-form-id').submit(function(evt) {
          evt.preventDefault();
          evt.stopPropagation();
          $('#edit-validation-hack').click();
        });
      }
    }
  })(jQuery, Drupal);

Hope this helps you, or anybody else that may stumble across this.

1
  • I just edited my answer to reflect a gotcha I just encountered. The hidden #ajax button needs to have a value assigned to ensure that it's called in all instances. If no value is specified and there are additional action buttons, it will call the #ajax on the last button if it has it or throw an exception stating that callback is empty or not callable.
    – konadave
    Jan 29, 2016 at 22:28

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.