How to create a custom ajax form in Drupal 8

Code With Travel
2 min readJan 27, 2020

--

Ajax is a script on the client side communicating asynchronously with the server without a complete page refresh. In order to build a simple form using AJAX in Drupal 8, we created a form with the User email field. Using ajax we are going to validate that field. To achieve this, create a custom module loremipsum it requires 3 files which are

  1. loremipsum.info.yml
  2. loremipsum.routing.yml
  3. src\Form\AjaxExampleForm.php.

The steps were listed below, how to validate the email field using AJAX.

Step 1: Create loremipsum.info.tml

name: loremipsum Module
description: An experimental module to build our first Drupal 8 module
package: Custom
type: module
version: 1.0
core: 8.x

Step 2: Create loremipsum.routing.yml file

loremipsum.ajax_example:
path: '/ajax_example'
defaults:
_form: '\Drupal\loremipsum\Form\AjaxExampleForm'
_title: 'Ajax Example'
requirements:
_access: 'TRUE'

Step 3: Create a form file. Path is custom\loremipsum\src\Form\AjaxExampleForm.php

<?phpnamespace Drupal\loremipsum\Form;use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Database\Database;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
/**
* Class loremipsumForm.
*
* @package Drupal\loremipsum\Form
*/
class AjaxExampleForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'ajax_example_form';
}
/**
* {@inheritdoc}
*/
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>',
);
$form['actions'] = [
'#type' => 'submit',
'#value' => $this->t('Submit1'),
'#ajax' => array(
'callback' => '::checkUserEmailValidation',
'progress' => array(
'type' => 'throbber',
'message' => NULL,
),
)
];
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
}/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
}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;
}
}

Here we define checkUserEmailValidation validation callback.

Now go to ajax_example URL and check form.

--

--

Responses (1)