A custom Drupal AJAX form in a working example module (Also sends emails and validates email address)
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 the Drupal example module contains:
- The AJAX form;
- A Block, so you can place it in some site region;
- A Twig html file for block markup;
- An implementation of hook_mail() to get the email sent.
Example end result
Te code is cloned from our support form, see the leading image above.
Copy and run off
We published it on Github 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.
The classes in the form are bootstrap's. So if you implement Bootstrap libs it will automatically look good / better.
Most important code to get AJAX working
- Add the AJAX callback and use '#type' = 'button', not '#type' = 'submit'.
- Add the libraries needed to get AJAX working.
- Initiate AJAX response.
- Add AJAX commands, a full list of Drupal core AJAX callback commands.
- 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.
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!