Blair Wadman 3 minute read

Creating a modal in Drupal 8 with one line of HTML

Modal dialogs are incredibly useful on websites as they allow the user to do something without having to leave the web page they are on. Drupal 8 now has a Dialog API in core, which greatly reduces the amount of code you need to write to create a modal dialog. Dialogs in Drupal 8 leverage jQuery UI.

In this first part in the series on the modal API in Drupal 8, we are going to create a search link in a block in the sidebar. When a user clicks on the search link, they will be presented with the modal with Drupal’s search form.

The first step is to add a block to the side bar. Head over to Block Layout and add it to a region of your choice. In this example, I’m going to add it to sidebar first.

Place a block button in Drupal 8

Select Add custom block.

Button to add a custom block in Drupal 8

In the block settings, change the text format to Full HTML and click on the Source button to remove the rich text editor. This will allow you to add a small HTML snippet without the rich text editor trying to encode the HTML.

In the body of the block, add the following snippet:

<p><a class="use-ajax" data-dialog-type="modal" href="/search/node">Search</a></p>

And now if you head back to the site, you will see the block in the side bar. Click on the search link, and you will get the modal.

Search modal

Adjusting the width

You can adjust the width by adding the data-dialog-options attribute:


I’m including the HTML entity &quot; because that will end up being a quote mark in the rendered HTML.

The full snippet with a width of 800 pixels is:

<p><a class="use-ajax" data-dialog-options="{&quot;width&quot;:800}" data-dialog-type="modal" href="/search/node">Search</a></p>

Wrapping up

You can use this method to display any valid Drupal path in a modal. For example, if you want to show a node in a modal, change the href to the path for the node.

<p><a class="use-ajax" data-dialog-options="{&quot;width&quot;:800}" data-dialog-type="modal" href="/node/2">See node 2</a></p>

These examples show the power of Drupal 8’s dialog API. With just a couple of attributes in a standard link, you can display any path in a modal.

This is a very simple example to help get you started. In most cases, adding modals is done in custom modules or themes. To find out how to do this in a custom module, check out the next tutorial in the series: Create a modal in Drupal 8 in a custom module