0

I'm testing a simple ajax modal link on a Drupal site and figured out that the modal

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

does only show when logged in as admin. For authenticated users it does not load (it just shows the search page). This is independent of the underlying theme I am using (bartik or a bootstrap subtheme). No error messages or status-reports give any indication what's going on. I thought only for anonymous users ajax needs to be added for the theme dependencies ? What am I missing here ?

  • 1
    see drupal.stackexchange.com/questions/238591/…, which was for anonymous users, but an additional question was, why it is working for an authenticated user and in this case the authenticated user already had the library loaded for other modal dialogs. For your authenticated user it is not working at the moment, so you have to add the library, which btw. is always the correct thing to do, because you don't know if the other functionality which is using the library already will stay in place. – 4k4 Nov 30 '17 at 9:49
1

For use-ajax to work for Anonymous as well as Authenticated user, Core core/drupal.ajax library must need to be loaded on page, where we're using 'use-ajax' class.

You can include this library with either using #attached in your Form or Controller or you can implement hook_page_attachments hook and attach ajax library.

If you're trying to add link to text inside your form, you can directly use #ajax instead of using classes as per directed in Ajax commands for opening and closing Dialogs and generic Dialog Controller added to core

  $form['link'] = [
    '#type' => 'link',
    '#title' => 'Link 1 (modal)',
    '#url' => Url::fromRoute('ajax_test.dialog_contents'),
    '#ajax' => [
      'dialogType' => 'modal',
    ],
  ];

Hope this helps.

  • Hi, just using #attached or using #ajax in the form did not solve my current problem. Adding the dependency to my theme did, as suggested by 4k4. However, using hook_page_attachments() sounds helpful as well, I did not know this before. – theuni Nov 30 '17 at 10:27
  • 1
    Normally you don't need this hook. Ideally the code which adds the modal link also adds the library. For example if you add the link to $build in a controller, then also attach the library to this build array $build['#attached']. Forms, blocks, field formatters etc. do the same. Then Drupal can render all parts of the website and the attachments from each element bubble up to the page. So each page loads only the libraries necessary for the specific content. – 4k4 Nov 30 '17 at 12:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.