Using AJAX in a Drupal form
The Form API has a mechanism to perform AJAX requests without writing any JavaScript. In this example, we will create a counter with an increment and decrement button.
How to do it…
- Create a file named
CounterForm.php
in thesrc/Form
directory for your module to hold theCounterForm
form class. - We will define the
CounterForm
class with a form ID ofmymodule_counter_form
:<?php
namespace Drupal\mymodule\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
class CounterForm extends FormBase {
public function getFormId() {
return 'mymodule_counter_form';
}
public function buildForm(array $form,
FormStateInterface $form_state) {
return $form;
}
public function submitForm(array &$form,
FormStateInterface $form_state) {
}
}
- In the
buildForm
method...