0

I want to open the create user form (/admin/people/create) into a specific div via AJAX. I can currently open such forms into a modal window using the following link format:

<a href="/admin/people/create" class="use-ajax" data-dialog-type="modal">
    Add user
</a>

Is there any way to load this form/page into a div instead of into a modal window?

1
  • 1
    If you down vote and mark a question to be closed, then be courageous enough to leave a comment about why and what is not clear about the question. Nov 12, 2020 at 14:42

1 Answer 1

2

Core does not provide an HTML format for non-dialogs, but you can create your own custom format.

mymodule/js/custom-ajax-loader.js:

(function ($, Drupal) {
  Drupal.behaviors.myCustomAJAXStuff = {
    attach: function (context, settings) {
      $("a.use-custom-ajax", context).once('mymodule-ajax').each(function(i, ajaxLink) {
        const $linkElement = $(ajaxLink);

        const elementSettings = {
          url: $linkElement.attr("href"),
          event: 'click',
          progress: {type: 'throbber'},
          element: ajaxLink,
        };

        const myAjaxObject = Drupal.ajax(elementSettings);

        // Declare a new Ajax command specifically for this Ajax object.
        myAjaxObject.commands.insert = function (ajax, response) {
          let target = $linkElement.attr("target");
          $(target).html(response.data);
        };
      });
    },
  };
})(jQuery, Drupal);

mymodule.libraries.yml:

mymodule.ajax:
  js:
    js/custom-ajax-loader.js: { }
  dependencies:
    - core/drupal.ajax

Add the library wherever needed: Adding stylesheets (CSS) and JavaScript (JS) to a Drupal module

Then when you create your link

<a href="/admin/people/create" class="use-custom-ajax" target="#some-div-id">
    Add user
</a>
6
  • Perfect! Thanks a million for your help. Can I edit your post to put my complete code, including defining the library etc? Nov 12, 2020 at 16:00
  • Go for it, do whatever changes you want. I was lazy to add the libraries stuff.
    – No Sssweat
    Nov 12, 2020 at 16:11
  • 1
    Thanks, done! :) Nov 12, 2020 at 16:24
  • I have a problem with the ajax loaded form. Maybe I should create another question, but I wanted to have your idea first. If I click on any "add another item" buttons on the form, the page is reloaded and redirects to /admin/people/create, breaking the whole ajax experience. Do you have any suggestion about this? Dec 14, 2020 at 11:55
  • @ЕлинЙ. You need to add url and options keys to #ajax of the "add another item" button. See for example Ajax submission not working for Webform within a node and for your route use user.admin_create
    – No Sssweat
    Dec 14, 2020 at 12:12

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.