1

I have no problems with using Ajax in every form element other then button. When I'm clicking this button

  '#type' => 'submit',
  '#ajax' => [
    'callback' => '::ajax_function',
    'wrapper' => 'my-button-wrapper',
  ],

it reloads the page ... well it does what would normal submit button do - calls submitForm(). And I don't need that. I need this button only to call ajax_function()

4

In Drupal, the submitHandler() method of your form definition will always be called UNLESS you have a custom handler attached to the submit button that is clicked. In the case of #ajax buttons, you add your own custom handler, then rebuild the form in that handler.

'#type' => 'submit',
'#ajax' => [
  'callback' => '::ajax_function',
  'wrapper' => 'my-button-wrapper',
],
'#submit' => ['::ajaxButtonSubmit'],

Then:

public function ajaxButtonSubmit(array &$form, FormStateInterface $form_state) {
  $form_state->setRebuild(TRUE);
}

By doing this, the default submit handler is not called, and your ajax submit handler is called instead, which then ensures the form is rebuilt instead of reloaded.

| improve this answer | |
  • There also was 'id' in '#attributes', it was interfering too – Den Aug 21 '19 at 11:45
  • Great answer, the custom submit handler is equally important as fallback when js is not available. – 4k4 Aug 21 '19 at 12:30
  • Good point! .... – Jaypan Aug 21 '19 at 12:42
  • And unfortunately it's not working – Den Aug 21 '19 at 18:37
  • I've used this many times on forms. It works. Re-check your code. – Jaypan Aug 21 '19 at 22:05

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.