How to build a simple form using AJAX in Drupal 8

Step 1: Create .info.yml

name: Ajax Example
description: User Name or Email  Ajax Validation
core: 8.x
type: module

Step 2: Creating .routing.yml Let’s create a .routing.yml called ajax_example.routing.yml. Each route is defined as a machine name in the form of module_name.route_name

path: '/ajax_example'
        _form: '\Drupal\ajax_example\Form\AjaxExampleForm'
        _title: 'Ajax Example'
        _permission: 'access content'

Step 3: Create AjaxExampleForm.php

Create a new file called AjaxExampleForm.php inside of src/Form/{AjaxExampleForm.php}.

getFormId() function is used to create a unique id to the form.

buildForm() function is used to create the form and it has a textfield to validate the username using #ajax. Drupal provides the property ‘#ajax’ to a form element in your form array, to trigger an Ajax response.

checkUserEmailValidation() is the callback function to handle the server side of the ajax event i.e., to check the user or email is already exists in the database or not.

 * @file
 * Contains Drupal\ajax_example\AjaxExampleForm

namespace Drupal\ajax_example\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;

class AjaxExampleForm extends FormBase {

  public function getFormId() {
    return 'ajax_example_form';
public function buildForm(array $form, FormStateInterface $form_state) {
   $form['user_email'] = array(
      '#type' => 'textfield',
      '#title' => 'User or Email',
      '#description' => 'Please enter in a user or email',
      '#prefix' => '<div id="user-email-result"></div>',
      '#ajax' => array(
         'callback' => '::checkUserEmailValidation’,
         'effect' => 'fade',
         'event' => 'change',
          'progress' => array(
             'type' => 'throbber',
             'message' => NULL,

Drupal provides user_load_by_name() function for getting the username and user_load_by_mail() function for getting the Email. To return commands, you need to set up an object of class Drupal\Core\Ajax\AjaxResponse and the addCommand method is used to add the individual command to it.

 public function checkUserEmailValidation(array $form, FormStateInterface $form_state) {
   $ajax_response = new AjaxResponse();
  // Check if User or email exists or not
   if (user_load_by_name($form_state->getValue(user_email)) || user_load_by_mail($form_state->getValue(user_email))) {
     $text = ‘User or Email is exists';
   } else {
     $text = ’User or Email does not exists';
   $ajax_response->addCommand(new HtmlCommand('#user-email-result', $text));
   return $ajax_response;

Step 4: Done. 
Source from GitHub

Related Post

Latest Post

Recent Posts Widget

Make sure to never miss a thing...

Get the latest news from the creative industry along with other creative goodies, conveniently delivered to social media.