8 – Creating a route that returns an AJAX Response that opens a modal


​I have this route that is suppose to render a block and two view blocks and then display them in a modal.

Originally, I had this route created in the Pages section of Structure, but then decided to create it in my module using this tutorial

However, when I construct it in my module, now it won’t open in a modal. It attempts to, but then just fails with no errors in the console or in Drupal, so I can’t debug the issue because I can’t even find out what the issue is… If I go to the route directly in the browser instead of through a link, it just prints out an array of command objects

Here’s my code:

my_module.routing.yml

my_module.my.results:
  path: "/user/results"
  defaults:
    _title: "My Results"
    _controller: 'Drupalmy_moduleControllerme3Controller::myResults'
  requirements:
    _user_is_logged_in: "TRUE"
    _is_ajax_request: 'TRUE'

myController.php

class myController extends ControllerBase {
  function myResults() {
    $renderer = Drupal::service('renderer');

    $top_careers_view = views_embed_view('top_careers', 'block_top_careers');
    $top_careers = $renderer->render($top_careers_view);
    $matched_degrees_view = views_embed_view('matched_degrees', 'block_matched_degrees');
    $matched_degrees = $renderer->render($matched_degrees_view);

    $content = $top_careers . $matched_degrees;

    $title = "Title";
    $options = (
      'dialogClass' => 'my_modal'
    );
    $response = new AjaxResponse();
    $response->addCommand(new OpenModalDialogCommand($title, $content, $options));

    return $response;
  }
}

my-template.html.twig

<a 
  class="use-ajax"
  data-dialog-type="modal" 
  data-dialog-options='{
    "dialogClass": "my-modal"
  }'
  href="/{{ language }}/my/results">{{ 'Match More Careers'|t }}
</a>

At one point I had /my/results_test created in Pages that I would open up in a modal via the html link:

<a 
  class="ytp-magenta-button use-ajax"
  data-dialog-type="modal" 
  data-dialog-options='{
    "dialogClass": "ytp-dashboard-me3-modal"
  }'
  href="/{{ language }}/my/results_test">{{ 'Match More Careers'|t }}
</a>

I also had the /my/results route still created in my module and if I created a modal-link (defined above) to it from one of the blocks in /my/result_test, then the /my/results route would open in a modal as expected.

So essentially, with what I have, I can open my modal route from another modal, but I can’t open it directly from a regular page…