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.phpin thesrc/Formdirectory for your module to hold theCounterFormform class. - We will define the
CounterFormclass 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
buildFormmethod...