Overview
It is assumed that you know how to create a form. If not, see Create a form in Drupal 8.
Form submission requires a page reload. What we want is to submit a form without refreshing the page. Drupal provides a way to do this using Ajax.
The process is still the same as creating a form but in your form class, simply use Ajax calls.
Create a routing for the form
Add the routing information in ./modules/tradesteps/tradesteps.routing.yml
, like the following:
tradesteps.my_form_ajax: path: '/my_form_ajax' defaults: _form: 'Drupal\tradesteps\Form\MyFormAjax' _title: 'My Form Ajax' requirements: _permission: 'access content'
Implement your form class
Now, you have to implement MyFormAjax
class.
Add the following code in ./modules/tradesteps/src/Form/MyFormAjax.php
.
<?php namespace Drupal\tradesteps\Form; use Drupal\Core\Form\FormBase; use Drupal\Core\Form\FormStateInterface; // Use for Ajax. use Drupal\Core\Ajax\AjaxResponse; use Drupal\Core\Ajax\HtmlCommand; class MyFormAjax extends FormBase { /** * Build the simple form. */ public function buildForm(array $form, FormStateInterface $form_state) { // Add input field called title. $form['title'] = [ '#type' => 'textfield', '#title' => $this->t('Title'), '#description' => $this->t('Title must be at least 15 characters in length.'), '#required' => TRUE, ]; // Attach Ajax callback to the Submit button. $form['actions']['submit'] = [ '#type' => 'submit', '#value' => $this->t('Submit'), '#ajax' => [ 'callback' => '::setMessage', ], ]; // Placeholder to put the result of Ajax call, setMessage(). $form['message'] = [ '#type' => 'markup', '#markup' => '<div class="result_message"></div>', ]; return $form; } public function setMessage(array $form, FormStateInterface $form_state) { $response = new AjaxResponse(); $response->addCommand( new HtmlCommand( '.result_message', '<div class="my_message">Submitted title is ' . $form_state->getValue('title') . '</div>') ); return $response; } /** * Implements a form submit handler. */ public function submitForm(array &$form, FormStateInterface $form_state) { // Nothing to do. Use Ajax. } public function getFormId() { return 'tradesteps_simple_form_ajax'; } }
Test the input form
- Clear your cache.
- Open http://your-domain.com/my_form_ajax
- Type in your title and then click on the Submit button.
Github
- https://github.com/xuanngo2001/drupal-form-ajax