Using Ajax Forms in Drupal 8

Originally published at: http://www.sitepoint.com/using-ajax-forms-drupal-8/

In this article, I am going to show you a clean way of using the Drupal 8 Ajax API without writing one line of JavaScript code. To this end, we will go back to the first custom form we built for Drupal 8 in a previous article and Ajaxify some of its behaviour to make it more user friendly.

An updated version of this form can be found in this repository under the name DemoForm (the demo module). The code we write in this article can also be found there but in a separate branch called ajax. I recommend you clone the repo and install the module in your development environment if you want to follow along.

DemoForm

Although poorly named, the DemoForm was very helpful in illustrating the basics of writing a custom form in Drupal 8. It handles validation, configuration and exemplifies the use of the Form API in general. Of course, it focuses on the basics and has nothing spectacular going on.

If you remember, or check the code, you’ll see that the form presents a single textfield responsible for collecting an email address to be saved as configuration. The form validation is in charge of making sure that the submitted email has a .com ending (a poor attempt at that but enough to illustrate the principle of form validation). So when a user submits the form, they are saving a new email address to the configuration and get a confirmation message printed to the screen.

In this article, we will move the email validation logic to an Ajax callback so that after the user has finished typing the email address, the validation gets automagically triggered and a message printed without submitting the form. Again, there is nothing spectacular about this behaviour and you will see it quite often in forms in the wild (typically to validate usernames). But it’s a good exercise for looking at Ajax in Drupal 8.

Continue reading this article on SitePoint

Good article. It is nice to see some quality info about Drupal, especially 8 coming out of none other than sitepoint.

1 Like

Thanks. I want just point to that the first method’s body could be much simplier in the form of below:

return (substr($form_state->getValue('email'), -4) === '.com');

There is no need for using if statement when we want to returning with a single boolean value.

Hehe, totally right :smile:
Thanks!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.