A place for ideas and experiments

Using Drupal 8 Modal API

Drupal 8 has come with many cool feature to trigger JavaScripts events from the Backend using classes like AjaxResponse and OpenDialogCommand. One of these cool features is the possibility to open modal windows to show content or forms in a modal window very very easily.

In this post I’ll show you how to use this API to put a simple HTML anchor to open and fill a modal window.

Preparing the Theme

In order to be able to use the modal API you need to include in your theme the jQuery UI scripts among other libraries required by Drupal. In your libraries.yml in your theme folder, be sure that under the dependencies branch you have these libraries to be included

If you have to do any change here be sure to rebuild the cache when the change is done.

The Frontend

This is the easiest part, you must include an anchor link with some attributes to indicate Drupal that you want to open a modal once is clicked. One of the attributes is the class with the value use-ajax, the second attribute is the data-accepts attribute that must have the value application/vnd.drupal-modal, last but not least, don’t forget to include the href attribute, without this attribute you will get a Js error and this API won’t work.