1

I have a form that looks like this:

$form['text'] = [
  '#type' => 'textfield',
  '#title' => $this->t('Text'),
  '#required' => TRUE,
  '#weight' => 0,
  '#ajax' => [
    'callback' => array($this, 'validateFieldAjax'),
    'event' => 'change',
  ]
];
$form['email'] = [
  '#type' => 'email',
  '#title' => $this->t('Email'),
  '#required' => TRUE,
  '#weight' => 0,
  '#ajax' => [
    'callback' => array($this, 'validateFieldAjax'),
    'event' => 'change',
  ]
];

$form['actions']['submit'] = [
  '#type' => 'submit',
  '#value' => $this->t('Submit'),
  '#attributes' => ['class' => ['use-ajax-submit']],
  '#ajax' => [
    'callback' => '::ajaxAfterSubmitAction',
    'event' => 'click',
  ],
];

What I want to have happen is:

  • When either field is changed, the callback happens and returns instructions to update the form; I don't want the form's validateForm to fire or for the form to submit.
  • When the submit button is clicked, the form validates and submits, then the ajaxAfterSubmitAction fires (which may update the form, or do something else depending on whether submit failed or succeeded).

What actually happens is: - The validateForm function gets called on every callback - When the validateFieldAjax callback happens, the ajaxAfterSubmitAction also happens, even though the button was not clicked. I'm really baffled about what's going on there.

I've seen this question -> How to omit form's validation at AJAX button click?, and tried adding |'#limit_validation_errors' => array(), '#submit' => array()| values to my text and email fields, but it doesn't seem to change anything.

I have found a work around by exploiting the fact that the submitForm action at least only happens after the submit button is clicked, using session variables to track when the 'real' submit action happens, and creating custom Callback Commands that ignore the nonsense returns from the ajaxAfterSubmitAction firing before it should. But I don't understand what's happening, and I'm sure there's a better way to do this. Can anyone help?


Edit: new thing I found out, if I add a 'prevent' => 'click' to the text and email fields, ie

'#ajax' => [
    'callback' => array($this, 'validateFieldAjax'),
    'event' => 'change',
    'prevent' => 'click'
  ]

The ajaxAfterSubmitAction no longer fires after the fields are updated. Which is good, but so confused. What's going on?


Edit: Scratch that last edit, it's gone back to the previous behaviour this morning.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.