Skip to main content

Drupal 9: Add a modal with specific node display-view mode from a custom route and how to modify the modal box properties

This is a code snippet that adds modal functionality for a link element with adding only an extra routing yaml file.

First you want to make sure you have the display mode of the node entity. For example the classic node.teaser (view mode). Then in your custom module add this routing.yml file (web/modules/custom/pixelthis/pixelthis.routing.yml).

pixelthis.routing.yml

employee.view:
  path: '/employee/card/{node}'
  defaults:
    _entity_view: 'node.teaser'
  requirements:
    _permission: 'access content'

This will open the modal with node teaser display - view mode but it is also accessible directly as a normal path.

Next in your twig file add this

<a class="use-ajax" 
data-dialog-type="modal" 
data-dialog-options="{&quot;width&quot;:424 ,&quot;height&quot;:450, &quot;dialogClass&quot;: &quot;employee-modal&quot;}" 
href="/employee/card/{{node.id}}">{{ 'Open Modal'|t }}</a>

Clear caches and click on the above link.  As you can see this will open the path declared in the pixelthis.routing.yml file. In this example I have included and some extra settings you can pass to the modal box so you can add some extra css styling. For example let's say you do not want the Modal Header - Title or you want different styles for only this modal (employee). Here I add the employee-modal css class to the modal classes and I can style this independent from all the other modal boxes.

You can also define the dimensions of the modal box by adding in the data-dialog-options "&quot;width&quot;:424 ,&quot;height&quot;:450".

modal