How to build a simple form using AJAX in Drupal 8

Ajax is a script on the client side communicating asynchronously with the server without a complete page refresh.The best description I came across about Ajax as “the method of exchanging data with a server, and updating parts of a web page — without reloading the entire page.”

In our project, while creating a new account if we give the existing username, on submitting the page it will throw an error. But, instead of reloading the page, we can just update certain parts of DOM. This can be achieved using AJAX. So, here is the example how to implement this ajax in drupal 8 forms.

In order to build a simple form using AJAX in Drupal 8 , we created a form with Username field. Using ajax we are going to validate that field. To achieve this, create a custom module ajax_example it requires 3 files which are ajax_example.info.yml, ajax_example.routing.yml, src\Form\AjaxExampleForm.php. The steps were listed below, how to validate the text field using AJAX.

Step 1: Create .info.yml

Let’s create a yml file. A yml file is a file that specifies the configuration for a file i.e., to store metadata information about the project

path: ‘/ajax_example’
defaults:
_form: ‘\Drupal\ajax_example\Form\AjaxExampleForm’
_title: ‘Ajax Example’
requirements:
_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' => 'Username or Email',
'#description' => 'Please enter in a username 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: Here is our Ajax output in drupal 8 Form. The main objective of this blog is to validate the existing username or email without reloading the page.

In drupal 8, we can achieve this by using ‘#ajax’ attribute and return the ajax response using the object of the class Drupal\Core\Ajax\AjaxResponse and added the individual command using addCommand method with the object of the class Drupal\Core\Ajax\HtmlCommand to show the message.

So, in this article, we have see an example regarding AJAX, to just update certain part of DOM, instead of reloading the whole page.

Also published on www.valuebound.com

Show your support

Clapping shows how much you appreciated Padma Priya’s story.