+31 20 - 261 14 99

Mr Treublaan 1-3
1097 DP Amsterdam
The Netherlands

A custom Drupal AJAX form in a working example module

Also sends emails and validates email address
14 Jun, 2020 Drupal

Home Blog A custom Drupal AJAX form...

Support ajax form example screenshot

While building this Drupal 9 site a few months ago we needed to handle the contact form. Normally we would use the Drupal Webform module, but that wasn't Drupal 9 ready enough at the time. So we decided to build the form ourself, AJAX based to make it as user friendly as possible and learn a few things. We published the complete code in a working, installable Drupal module. A small explanation:

So you the Drupal example module contains:

  • The AJAX form
  • A Block, so you can place it in some site region.
  • A Twig file for block markup.
  • An implementation of hook_mail() to get the email sent.

Example end result

Te code is cloned from the support form on getlucius.com:

Copy and run off

We published it so you can copy it and run off with it to do whatever you need, so at the moment it's not a published Drupal.org project with all kinds of configurable stuff.

Bootstrap based

The classes in the form are bootstrap's. Zo if you implement Bootstrap libs it will automatically look good / better.

Most important code to get AJAX working

  1. Add the AJAX callback and use '#type' = 'button', not '#type' = 'submit'.
  2. Add the libraries needed to get AJAX working.

  1. Initiate AJAX response.
  2. Add AJAX commands, a full list of Drupal core AJAX callback commands.
  3. Return response.

Flood protection, honeypot and code optimisation

There is no flood protection added yet, and if you like to implement Honeypot then uncomment line 103 in AjaxContactForm.php

Of course code can be optimised, there is a too big procedural if/else and a Drupal Service might come in handy, also mail bodybuilding is not quite. But I think you'll git the pic by now (:

Drupal 'quick-start'

PS, to test this module fast in a fresh Drupal install, Drupal's quick-start comes in very handy.

Find the code on Github

Download or view the code here on Github.

Like to see this as a contrib Drupal module?

Please let me know, if there is enough positive feedback on this we might make it configurable and contrib it!

Got some more time?

Related content
15 Apr, 2021 Drupal

For background and text in each row/section/block/component

08 Apr, 2021 Drupal

A ~3 year journey (be careful with ReactJS, MongoDB and other external tech)

05 Mar, 2021 Drupal

Let's Talk

Pease tell me all about your project.
+31 (0)20 - 261 14 99  /  joris@lucius.digital.