A custom Drupal AJAX form in a working example module (Also sends emails and validates email address)

Jun 14, 2020

Joris Snoek
Founder /
Business Consultant

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!

Comments

Need even
more knowlegde?