Creating custom modal with form in Drupal 8

A modal in Drupal 8 can be triggered by just adding this single line:

_config.yml

Important: Make sure to add drupal core library ‘core/drupal.dialog.ajax’ to call ajax modal to the page triggering the modal.

Before start learning how to create custom modal, checkout the following repository: https://github.com/vatsalkhanna1992/custom_modal

Step 1: Create info.yml

Create info.yml file which will include information about our custom module:

_config.yml

Step 2: Create controller

Now, create a controller file which will display our custom modal. So, first create routing.yml file which defines the controller.

_config.yml

This will define our controller from where the modal will get triggered. Then, create controller file:

_config.yml

The ModalController should extend ControllerBase.

Step 3: Create form

Create a Form:

_config.yml

Step 4: Call form and OpenModalDialogCommand()

Once the form is created, call this form through controller using “$form = \Drupal::formBuilder()->getForm()”. Now create modal by creating object of OpenModalDialogCommand() inside ajax response.

_config.yml

This will create a modal and set its width. Then, its wrapped into AJAX response object.

Step 5: Create block to trigger modal

Now, create a block, which contains a button to trigger modal.

_config.yml

Make sure, ‘core/drupal.dialog.ajax’ library is attached to the block. This will trigger the response as modal.

Written on October 9, 2018