Skip to main content

Drupal 8 i Modalni obrasci (english)

Adding a modal form to capture some data from visitors is a common client request. This may look like a simple feature to code by yourself, but it usually isn't. Why? Because you have to store captured data somewhere, and that means creating a new entity. You also have to take care about form validation and security. Sometimes you also have to send the captured data to email addresses.

Why waste your valuable time to code all this, when there is a simpler and better solution. And that solution is the Webform module. This module is actively developed and has a ton of options. And one of those options is to create modal forms. Let's see how you can do that.

The first thing that you need to do is to actually install and enable the Webform module. You can use Composer and Drush to do that:

composer require drupal/webform
drush en -y webform

Now, go to the following page: /admin/structure/webform and you'll see the list of available forms. When you install the Webform module it will create the Contact form for you by default. I'll use this form as an example.

Before you do anything you have to enable modal form support. Visit this page: /admin/structure/webform/config and check "Enable site-wide dialog support".

Webform modal configuration


The last thing that you have to do is to create a link and add some special classes. To display the Contact form in a modal create a link like this:

<a class="webform-dialog webform-dialog-narrow" href="/form/contact">Contact us</a>

If you want to create a button instead of a text link just add the button class like this:

<a class="webform-dialog webform-dialog-narrow button" href="/form/contact">Contact us</a>

You can add these links in a Twig template or you can add it in text fields of blocks and pages.

So, to recap.

  1. Install and enable the Webform module.
  2. Enable dialog support.
  3. Add a link with special classes

Of course, you don't have to use the default contact form, you can create a new form. Just remember to change the href attribute to point to a new webform.