Issue Summary

  • #46 Describes the problem as to why the issue is happening which generally narrows down to hard coding of html ids for modal opening and closing command.
  • #48 Provides a solution so that each open and close command can work with separate modal ids, It also provides a solution for media library form.
  • #73 Extracts the open and close command modifications from #48 so that it can be merged with core first and then for each individual case a separate issue and patch can be added.

Proposed resolution

  • Review and merge #73 or #48 in core.
  • Create individual issues for each possible use case like media library, Ckeditor etc.
  • Add the change records.

Original Post

I am currently looking into running CKEditor in a modal dialog using the Drupal Modal API.

At this moment it is working OK, but there is a problem with the link and image modals which can be triggered from the CKEditor interface. Those also use the Modal API and when triggering one of these functions, the modal containing CKEditor is fully closed.

Is there any way to open de link/image modal without closing the CKEditor modal? It seems like it is possible to define the HTML element to which the modal should append when triggering. When overriding this setting ('appendTo' => '#foo'), even the link/image modals are appended to #foo (instead of the default '#drupal-modal').

Any ideas on how to get this to work?
Thanks for your support.

CommentFileSizeAuthor
#126 interdiff-123-126.txt1.09 KBnuez
#126 2741877-126-d10.2.patch16.28 KBnuez
#125 interdiff.txt639 bytesdinazaur
#125 2741877-125.patch16.33 KBdinazaur
#123 2741877-123-D10.2.patch15.69 KBleymannx
#121 2741877-121.patch16.36 KB_utsavsharma
#121 interdiff_119-121.txt600 bytes_utsavsharma
#119 2741877-119-D10.1.patch16.23 KBpcambra
#119 2741877-119-D11.patch16.33 KBpcambra
#118 2741877-118.patch16.22 KB_utsavsharma
#118 interdiff_117-118.txt648 bytes_utsavsharma
#117 2741877-11.x-117.patch13.76 KBa.dmitriiev
#117 2741877-10.1.6-117.patch13.67 KBa.dmitriiev
#115 2741877-10.1.5-115.patch16.32 KBa.dmitriiev
#114 2741877-10.1.2-114.patch16.32 KBa.dmitriiev
#113 2741877-113.patch16.42 KB_utsavsharma
#113 interdiff_111-113.txt16.42 KB_utsavsharma
#111 2741877-111.patch16.32 KBlarowlan
#111 2741877-111-do-no-test-10-point-0.patch16.23 KBlarowlan
#111 interdiff-673f7b.txt1.24 KBlarowlan
#109 2741877-10point1-109.patch15.62 KBlarowlan
#109 2741877-10.0-109-do-not-test.patch15.61 KBlarowlan
#108 2741877-do-not-test-d10point0.patch9.71 KBlarowlan
#106 2741877-91-workaround-10.1.patch9.31 KBarnaud-brugnon
#102 bug.png122.25 KBFabsgugu
#91 2741877-91-workaround.patch9.7 KBAJV009
#82 2741877-82.patch5.12 KBGauravvvv
#81 interdiff-2741877-77-81.txt2.12 KBvakulrai
#81 nested_modal_media-2741877-81.patch4.93 KBvakulrai
#77 2741877-77.patch2.81 KBKapilV
#73 2741877-73-selector-only.patch2.81 KBtimodwhit
#70 interdiff_67-70.txt783 bytesraman.b
#70 2741877-70.patch17.04 KBraman.b
#67 2741877-nested_modals-67.patch17.04 KBjastraat
#66 2741877-nested_modals-66.patch103.87 KBjastraat
#58 screenshot.jpg271.95 KBR_H-L
#54 2020-04-28_15-29-37.png75.74 KBBinaryBlock
#54 2020-04-28_15-25-47.png107.64 KBBinaryBlock
#54 2020-04-28_15-22-46.png41.87 KBBinaryBlock
#54 2020-04-28_15-20-26.png64.75 KBBinaryBlock
#54 2020-04-28_15-18-17.png24.66 KBBinaryBlock
#54 2020-04-28_15-16-03.png23.87 KBBinaryBlock
#48 interdiff-46-48.patch657 bytesnuez
#48 2741877-48.patch17.04 KBnuez
#46 2741877-46.patch17.04 KBnuez
#46 interdiff-42-46.txt9.88 KBnuez
#42 interdiff-41-42.txt18.41 KBnuez
#42 2741877-42-test-only.patch10.78 KBnuez
#42 2741877-42.patch18.22 KBnuez
#40 2741877-41.patch5.09 KBnuez
#26 drupal-2741877-26.patch983 bytesmikhailkrainiuk
#26 ckeditor_popup_in_popup.png49.85 KBmikhailkrainiuk
#11 Screen Shot 2016-10-15 at 1.12.08 PM.png465.27 KBjrockowitz
#11 yamlform-modal-in-modal-issue.gif2.16 MBjrockowitz
Support from Acquia helps fund testing for Drupal Acquia logo

Comments

vollepeer created an issue. See original summary.

Wim Leers’s picture

Title: Use of CKEditor in a modal » Nested modals don't work: when using CKEditor in a modal, then clicking the image button opens another modal, which closes the original modal
Component: ckeditor.module » ajax system
Issue tags: +JavaScript

This is really about nesting of modal dialogs. I'd swear there is an issue for this, but I can't find it.

droplet’s picture

Component: ajax system » ckeditor.module
Category: Support request » Task

hmm....It seems we can improve it by changing CKEditor dialog to a unique ID. Any thoughts @WimLeers / maintainers?
https://github.com/drupal/drupal/blob/8.2.x/core/misc/dialog/dialog.ajax...

Wim Leers’s picture

Component: ckeditor.module » ajax system

This is a generic problem. What if something triggers a modal while already within a modal? That should work. This is not at all CKEditor-specific.

vollepeer’s picture

Indeed, same goes for the link modal.

Wim Leers’s picture

@vollepeer: can you explain that a bit?

Wim Leers’s picture

Oh, now I found that issue I was looking for in #2 — turns out @vollepeer was the one who opened it! It's #2737319: Opening a modal from inside another modal (nested modals), I marked it as a duplicate of this issue.

vollepeer’s picture

Sorry about the duplicate issue Wim :-)
Ignore my comment about link dialog: it is also in the context of CKEditor (image dialog + link dialog).

Indeed it relates to modals in general. However, like Droplet mentions, the modals triggered using the Drupal 8 Modal API seem to all be using the same parent HTML element. That wouldn't be an issue if new modals were attached to the element. But it seems like before opening a new modal, existing modals (if any) are cleared/destroyed.

Wim Leers’s picture

Hah, no worries :) Can be confusing/overwhelming to find your way through the Drupal core issue queue :) Hopefully my triaging helps.

Version: 8.2.x-dev » 8.3.x-dev

Drupal 8.2.0-beta1 was released on August 3, 2016, which means new developments and disruptive changes should now be targeted against the 8.3.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

jrockowitz’s picture

I have ran into this issue with the YAML Form module's UI where I am relying on modals.

Below is an animated GIF documenting my issue.

It is worth noting that the Token module's dialog does not replace the YAML Form module's dialog because the Token module is opening a dialog and not a modal.

droplet’s picture

Considered the BC, I thought it should be opt-in (to open another Modal) than opt-out (close old instance).

Instance A:
In general, by design. If I make a module and expected anything working inside a Modal. I will set a unique ID for the dialog (It's already supported in CORE, like the Token does)

Instance B:
In another case, take the CKEditor as example, I'd thought:

B1. If we designed the CKEditor buttons Modal always pop up to TOP layer and hidden all other elements. Then, other modules should listen to its callback and restore the old windows.

B2. If we designed the CKEditor buttons worked inside Modal BY DEFAULT, then we should create a unique ID for the CKEditor buttons dialog.

Personally, with CKEditor example, I preferred B2. Just like what the Token does in above screenshot.

Instance A & B have no conflicts, it can be done at same time.

Let me know if I'm missing some important points. :)

Anonymous’s picture

Version: 8.3.x-dev » 8.4.x-dev

Drupal 8.3.0-alpha1 will be released the week of January 30, 2017, which means new developments and disruptive changes should now be targeted against the 8.4.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Anonymous’s picture

Damn, I just found this issue myself http://drupal.stackexchange.com/questions/226980/image-upload-replaced-m...
Can't we use dialog instead of modal for the image?

Cauliflower’s picture

This issue is also related to this one: #2836043 (https://www.drupal.org/node/2836043)

Anonymous’s picture

Category: Task » Bug report

Aaah, this goes for links as well. Like 50% of the buttons are unusable like this. If there would be modal form in the core that would use any of these it would be a major bug. Unfortunately it is not :(

droplet’s picture

Issue tags: +Needs UX review, +Needs accessibility review

Tagging 2 tags to see what their thoughts on these usages. (also on Comment #12)

"Single Modal all-time" vs "Nested Modal" vs "BOTH"

andy_w’s picture

In the event that you need to go against the drupal defined method of a single modal window - which in turn prevents the use of nested modal window - you could use the OpenDialogCommand rather than OpenModalDialogCommand with the modal option set to true. This would allow you to use nested modals in the context of a built module.

Wim Leers’s picture

Category: Bug report » Task

This is really more of a feature request than anything else. Using nested modals is a bad practice.

Version: 8.4.x-dev » 8.5.x-dev

Drupal 8.4.0-alpha1 will be released the week of July 31, 2017, which means new developments and disruptive changes should now be targeted against the 8.5.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Version: 8.5.x-dev » 8.6.x-dev

Drupal 8.5.0-alpha1 will be released the week of January 17, 2018, which means new developments and disruptive changes should now be targeted against the 8.6.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

dsnopek’s picture

If there would be modal form in the core that would use any of these it would be a major bug. Unfortunately it is not :(

Do dialogs in the Views UI count?

See #2900594: CKEditor not available for Views "text" areas

tibezh’s picture

Hi All!

I had same issue.

For calling a modal window we should add a "data-dialog-type" attribute. This attribute accepts the values "modal" or "dialog".

I had the "modal" value.
After changing the value to "dialog" the modals from CKEditor it seems work

Version: 8.6.x-dev » 8.7.x-dev

Drupal 8.6.0-alpha1 will be released the week of July 16, 2018, which means new developments and disruptive changes should now be targeted against the 8.7.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

mikhailkrainiuk’s picture

Status: Active » Needs review
FileSize
49.85 KB
983 bytes

Hello!

@tibezh nice idea! :)
I had the same issue. I open popup (modal dialog) and when I click by "link" button, I see just one popup with link settings.
I updated ckeditor module and it works for me - see the screenshot. It shows popup over popup.

I created the patch to fix it. Verify it, please.
Thank you!

mikhailkrainiuk’s picture

Status: Needs review » Active

Hmm... Sorry, there are errors already. When I click by "Save" on link popup, it closes parent modal.

On my local project I fixed it: I set "dialog" type for my modal and "modal" type for ckeditor, it works correctly.
But it is a custom solution.

Version: 8.7.x-dev » 8.8.x-dev

Drupal 8.7.0-alpha1 will be released the week of March 11, 2019, which means new developments and disruptive changes should now be targeted against the 8.8.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

dabbor’s picture

I needed to solve this problem as this is blocking having any configurable modal form with fields as any configurable modal form can contain wysiwyg (with ckeditor and thus nested modals in form of image/link modal).

The working nested modal windows idea for my workaround:

  1. Change the main #drupal-modal id on the first modal window just before the second level modal is opened.
  2. Disable the main #drupal-modal window to be disabled while the second level modal is active/opened.
  3. Return back the main #drupal-modal id to the first modal window just after the second level modal is closed.

Even though each dialog window has its own specific id (using hash to be certain about it), the #drupal-modal id is being used as the main identifier (like a shortcut to make the logic/implementation easier). Opening and closing modal dialog is done through jQuery dialog plugin and the id specific to each dialog window is being used.

To support nested modal dialogs we just need to create dialog ids stack and change the #drupal-modal id to something else when getting one level higher and returning it back when moving down. Disabling the lower level dialogs is also required so that user can’t interact with them while working with the active one (the top one).

Additionally I had to create "BeforeOpenDialogCommand" (an AJAX command) that and alter AJAX responses to send it before "OpenDialogCommand". This way I was able to modify modal ids and z-index (to disable it) before new modal dialog was open. Including creating a new placeholder for modal window by:

<?php
$('<div id="drupal-modal" class="ui-front"/>').hide().appendTo('body');
?>

Later on using $(window).on('dialog:afterclose', function (e, dialog, $element) {...} to remove that placeholder and set the previous modal id and z-index back.

I would vote for having somethng like that in core. It might be not the best practise to use nested modals, mostly going more then two levels, but forbidding it by not implementing generic solution for modals, while there's no technical obsticle, seems bad practise to me.

Version: 8.8.x-dev » 8.9.x-dev

Drupal 8.8.0-alpha1 will be released the week of October 14th, 2019, which means new developments and disruptive changes should now be targeted against the 8.9.x-dev branch. (Any changes to 8.9.x will also be committed to 9.0.x in preparation for Drupal 9’s release, but some changes like significant feature additions will be deferred to 9.1.x.). For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

dercheffe’s picture

Issue tags: -JavaScript +JavaScript

stumbled over this issue because I run into the same problem. bump this issue :)

johnwebdev’s picture

The Layout Builder Modal module had a similar issue, and what we did was that we use the dialog type dialog instead of modal, and then having the option modal as true for the dialog rendering the CKEditor.

I noticed that the suggestion has already been commented earlier, would that option work for you @dercheffe?

dercheffe’s picture

Hi @Johndevman,

thanks for your reply.

I tried the patch provided in #26 and the proposed solution (I guess you mean this solution?) in general it's working fine. but I experienced the same errors/behaviours mentioned in #27.

tobiberlin’s picture

Hey... the same issue appears in Media Library when Media entities have a text field with CKEditor enabled:

- media entity "image" has a text field "copyright", where a CKEditor is used with a link button
- a node entity has a media field referencing media entities of type image, the form widget is Media Library
- when I upload a new image in the Media Library I can edit the image fields within the modal of the Media Library. Here I see my copyright field. When I click on it the whole modal is filled by the fields for link plugin. When I fill in the fields and click "Save" nothing happens

tobiberlin’s picture

Just to add another finding: when I use the Table plugin of CKEditor within a textfield the problem does not appear. The Table plugin seems to use the "cke_dialog". So it opens another modal ("cke_dialog") over the modal where CKEditor field is rendered in ("ui-dialog").

tobiberlin’s picture

I am not able to go in deeper by now but I want to share my findings so far:

  • Both Drupal CKEditor plugins causing the problems (links and images) call Drupal.ckeditor.openDialog to open the forms for the plugins in a modal loading some data with Ajax. The Drupal method is defined here: httpdocs/core/modules/ckeditor/js/ckeditor.js
  • The CKEditor table plugin uses CKEDITOR.dialog.add.

Maybe someone else with more JavaScript skills may have a look on this. It seems to me that best solution is to refactor Drupal.ckeditor.openDialog in a way that might be similar to CKEDITOR.dialog.add?

xjm’s picture

Issue tags: -needs UX review +Needs usability review
mrzapp’s picture

For anyone stumbling across this thread wanting a terrible hack that work right now, you can use this:

(function ($) {
    Drupal.behaviors.mymodule = {
    	attach: function(context, settings) {
            if(!Drupal.ckeditor) { return; }

            Drupal.ckeditor.openDialog = function openDialog(editor, url, existingValues, saveCallback, dialogSettings) {
                var $existingDialog = $('#drupal-modal').attr('id', 'drupal-modal-background');
                
                var $target = $(editor.container.$);

                if (editor.elementMode === CKEDITOR.ELEMENT_MODE_REPLACE) {
                    $target = $target.find('.cke_contents');
                }

                $target.css('position', 'relative').find('.ckeditor-dialog-loading').remove();

                var classes = dialogSettings.dialogClass ? dialogSettings.dialogClass.split(' ') : [];
                classes.push('ui-dialog--narrow');
                dialogSettings.dialogClass = classes.join(' ');
                dialogSettings.autoResize = window.matchMedia('(min-width: 600px)').matches;
                dialogSettings.width = 'auto';

                var $content = $('<div class="ckeditor-dialog-loading"><span style="top: -40px;" class="ckeditor-dialog-loading-link">' + Drupal.t('Loading...') + '</span></div>');
                $content.appendTo($target);

                var ckeditorAjaxDialog = Drupal.ajax({
                    dialog: dialogSettings,
                    dialogType: 'dialog',
                    selector: '.ckeditor-dialog-loading-link',
                    url: url,
                    progress: { type: 'throbber' },
                    submit: {
                        editor_object: existingValues
                    }
                });

                ckeditorAjaxDialog.execute();

                window.setTimeout(function () {
                    $content.find('span').animate({ top: '0px' });
                }, 1000);

                Drupal.ckeditor.saveCallback = function(returnValues) {
                    saveCallback(returnValues);

                    var $dialog = $('div[id^="drupal-dialog-editorlink-dialog"]').parent();
                
                    if($dialog.hasClass('ui-dialog')) { $dialog.dialog().dialog('close'); }

                    $dialog = $('div[id^="drupal-dialog-media-libraryui"]').parent();
                    
                    if($dialog.hasClass('ui-dialog')) { $dialog.dialog().dialog('close') }

                    window.setTimeout(function() {
                        $('#drupal-modal-background').attr('id', 'drupal-modal');
                    }, 1000);
                };
            };
     	}
	};
}(jQuery));

dpi’s picture

Title: Nested modals don't work: when using CKEditor in a modal, then clicking the image button opens another modal, which closes the original modal » Nested modals don't work: opening a modal from a modal closes the original

I think we agreed earlier in this issue that the issue isnt specific to CKeditor

nuez’s picture

Category: Task » Bug report
Status: Active » Needs review
FileSize
5.09 KB

Current situation

  1. Every OpenModalDialogCommand puts the modal in a wrapper with id #drupal-modal.
    Every CloseModalDialogCommandmakes all HTML elements with #drupal-modal disappear. So if two subsequent modals have been opened, both having #drupal-modal (which is not correct HTML), then both will get closed upon CloseModalDialogCommand.
  2. I think the reason that this one and only ID is required is to avoid having two modals of the same type being opened at the same time and causing heavoc. However currently it means that two modals of any type cannot be opened at the same type. It should be possible to have one modal of one type and the other of another type interacting with each other.
  3. In OpenModalDialogCommand::34 parent::__construct('#drupal-modal', $title, $content, $dialog_options, $settings); the ID is hardcoded.

My proposal

  1. Allow the Open and Close Modal commands to receive an ID. If there is no ID, then base the ID on the the path of the request that's being opened inside the modal, and if there is no request, just use #drupal-modal. That way where possible the modal is given a more context aware id.
  2. I've tried this with: ckeditor modals in modals work, and also media library field widgets within a modal.
  3. Obviously this needs tests, but I would love to hear any feedback about this approach. Also running the test bot to see what comes back.

Afterthoughts

#20: This is really more of a feature request than anything else. Using nested modals is a bad practice.

Whether or not this is bad practice can be debated (I think that depends entirely on the use case.)

Independently, I would still qualify this issue as a bug since Drupal Core allows any url to be opened in a dialog by adding class="use-ajax" data-dialog-type="modal" to any link, including, say, links to node forms. On the other hand core opens modals from ckeditor (image) and in widgets (media library). So a modal in a modal is very much core functionality IMHO.

I'm marking this as a bug again, but feel free to put it back to 'task'.

Status: Needs review » Needs work

The last submitted patch, 40: 2741877-41.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

nuez’s picture

Issue summary: View changes
Status: Needs work » Needs review
FileSize
18.22 KB
10.78 KB
18.41 KB

This is - perhaps not unexpectedly - a lot more complex than it looks.

If there is no ID, then base the ID on the the path of the request that's being opened inside the modal, and if there is no request, just use #drupal-modal.

My idea was to add some sort of 'context' to the ID of the modal, but this context is not consistently available to be able to use it.

I'm uploading a new patch that uses the State System to assign and check for a random ID string to each modal. This is probably far from ideal, but I hope it's the start of a solution. I also have not looked into the JS side of things.

New patch includes tests for:

  1. Opening the Media library plugin in CKEDITOR from a modal
  2. Opening the Media library widget from a modal.

I'm adding a test-only patch to prove that things are currently not working and are working with the proposed solution (I hope).

Tests that were previously breaking are now working. Curious to see if the testbot has any other complaints.

nuez’s picture

Issue summary: View changes

The last submitted patch, 42: 2741877-42.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

Status: Needs review » Needs work

The last submitted patch, 42: 2741877-42-test-only.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

nuez’s picture

Status: Needs work » Needs review
FileSize
9.88 KB
17.04 KB

OK, so:

  1. By design, subsequent modals should close the previously opened modals. An example can be found in the Views UI module, where subsequent modals for example for adding fields, close the previously opened modals.
  2. All modals share a single 'namespace', so to speak, in the form of the '#drupal-modal' HTLM ID. As a consequence, all modals are closed upon firing a new modal, including modals that shouldn't be closed.
    E.g. If the views UI were itself to be shown inside a parent modal, then all interaction would break because subsequent modals would delete the parent modal.
  3. This patch allows the OpenModalDialogCommand and the CloseModalDialogCommand to 'scope' the modals, by adding a selector.
  4. Sometimes modals are rendered by the ModalRenderer, which just receives a render array. This is the case for the modals opened by CKEditor buttons.

    It's well beyond my level of understanding how we should make ModalRenderer aware of the scope of the modal: For now I've added a render array property called '#modal_selector', which can be used to pass the scope of modal, which should probably be declared somewhere. Maybe even required with a @trigger_error.

  5. In this patch I've only 'scoped' the modals in the Media Library module, but also the modals in Views UI could be scoped by adding corresponding identifier to ViewsFormBase.php. That way you would be able configure views within a modal.
  6. Currently, if no scope is defined, the modal gets the original '#drupal-modal' global scope, meaning that it cannot be used inside another modal.

Questions?

  1. Should the 'scope' be compulsory for all modal interactions?
  2. If there is no scope present, and #drupal-modal is used, should there be a smarter error reporting or something showing a message that the modal is not allowed in another modal, instead of just breaking?
  3. How should the ModalRenderer know of the scope?

Looking forward to hear any feedback

Status: Needs review » Needs work

The last submitted patch, 46: 2741877-46.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

nuez’s picture

Status: Needs work » Needs review
FileSize
17.04 KB
657 bytes

With a bug, all tests should pass now. 2741877-46-48.patch is the interdiff.

johnwebdev’s picture

Thanks for working on this nuez!

+++ b/core/lib/Drupal/Core/Render/MainContent/ModalRenderer.php
@@ -33,7 +33,8 @@ public function renderResponse(array $main_content, Request $request, RouteMatch
+    $modal_selector = $main_content['#modal_selector'] ?? NULL;

+++ b/core/modules/media_library/src/Form/AddFormBase.php
--- a/core/modules/media_library/src/MediaLibraryUiBuilder.php
+++ b/core/modules/media_library/src/MediaLibraryUiBuilder.php

+++ b/core/modules/media_library/src/MediaLibraryUiBuilder.php
@@ -122,6 +122,7 @@ public function buildUi(MediaLibraryState $state = NULL) {
+        '#modal_selector' => '#modal-media-library',

Is this a new default template variable? This would need some documentation.

How would I set this scope selector when using data- attributes? i.e

        'class' => ['use-ajax', 'button', 'button--small'],
        'data-dialog-type' => 'modal',
        'data-dialog-options' => Json::encode(['width' => 400]),
nuez’s picture

Is this a new default template variable? This would need some documentation.

This definitely needs documentation. I see #modal_selector as a render array property like #cache, which would possibly be required the Modal Renderer. However, even if 'scoping' the modals is the right approach, there are probably still dozens of different solutions to this. I think the maintainers of the different subsystems involved need to say something about this from here.

How would I set this scope selector when using data- attributes? i.e

Maybe the scope doesn't have to be set in data attributes, modals created with the data attributes might get their own scope internally.

johnwebdev’s picture

Maybe the scope doesn't have to be set in data attributes, modals created with the data attributes might get their own scope internally.

As long as it's predictable I think that could work as well!

DanielVeza’s picture

Issue tags: +Needs change record

Amazing work. I just came across this issue today when using Linkit and Media Library together, and this patch solves that issue + tests pass. Really nice!

I just left a couple of tiny comments. Neither of them are blockers or anything that should break, just clarity changes. Happy for them both to be ignored if people disagree.

This will also need a change record I assume.

I'll leave this at needs review for now. But functionality wise this is RTBC from me.

  1. +++ b/core/lib/Drupal/Core/Ajax/OpenModalDialogCommand.php
    @@ -29,10 +29,13 @@ class OpenModalDialogCommand extends OpenDialogCommand {
    -    parent::__construct('#drupal-modal', $title, $content, $dialog_options, $settings);
    +    parent::__construct($selector ?: '#drupal-modal', $title, $content, $dialog_options, $settings);
    

    Tiny nitpick - Can we take the ternery out of the function call?

    Happy to be overridden on that. I'm just not a fan of logic in function calls personally.

  2. +++ b/core/lib/Drupal/Core/Render/MainContent/ModalRenderer.php
    @@ -33,7 +33,8 @@ public function renderResponse(array $main_content, Request $request, RouteMatch
    +    $modal_selector = $main_content['#modal_selector'] ?? NULL;
    +    $response->addCommand(new OpenModalDialogCommand($title, $content, $options, NULL, $modal_selector));
    

    Even though we can see the doc comment I think it could be valuable to add an inline comment here.

HeikeT’s picture

tested @DanielVeza patch with Linkit and Media Library. Working well! +1 Ta!

BinaryBlock’s picture

@nuez ... Thank you for the patch! @DanielVeza thank you for testing it!

I have been following this issue for a while now and trying to code something myself without any real luck.

I am experiencing a problem with the patch though. I am running Drupal 8 v8.8.4 with your patch.

Here are the steps to reproduce my problem:

  • Create new basic page.
  • In CKEditor (WYSIWYG) I select the "Insert from Media Library" icon any my first Modal/Dialog opens. screenshot
  • If I choose to "Add file" screenshot 2
  • Then choose my image, add details, and then open addition modal/dialog by adding a link in the Caption CKEditor. screenshot 3
  • This all works great, because the multiple modal/dialog issue is resolved by the patch and the background/parent dialogs are not getting closed on me. screenshot 4
  • Then I click Save on Add Link dialog and then Save again... I see the new media I just added and it's checkbox is preselected. screenshot 5
  • When I click "Insert Selected" it does not insert the added media into the original CKEditor.

I am able to re-open the "Insert from Media Library" and re-selected the added media... then if I click "Insert Selected" it puts it into the CKEditor properly.
screenshot 6

Somehow it seems that the first modal/dialog is losing its callback ability. Maybe something with scope... not sure. If we're able to get this functionality back with this patch it will solve everything we're trying to do with our team!

Thank you in advance for any help or advice you can provide.

DanielVeza’s picture

Tiny thing. @nuez made the patch and deserves all the kudos. I just reviewed it :D.

I'll have a look at that issue when I get some time. I don't think I was seeing that happen but I'll double check.

thetaPC’s picture

Patch #48 works, but I get the following errors when using Drupal core v. 8.8.4 Media Library and Focal Point v. 8.x-1.2:

Warning: unlink(/Users/*/Desktop/sites/*/sites/default/files/styles/*/public/2020-04/*.jpg): No such file or directory in Drupal\Core\File\FileSystem->unlink() (line 124 of /Users/*/Desktop/sites/*/core/lib/Drupal/Core/File/FileSystem.php)

Failed to unlink file 'public://styles/*/public/2020-04/*.jpg'.

Version: 8.9.x-dev » 9.1.x-dev

Drupal 8.9.0-beta1 was released on March 20, 2020. 8.9.x is the final, long-term support (LTS) minor release of Drupal 8, which means new developments and disruptive changes should now be targeted against the 9.1.x-dev branch. For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

R_H-L’s picture

FileSize
271.95 KB

Using Focal Point 1.4 with the latest Media Library patch (https://www.drupal.org/project/focal_point/issues/3094478), this works almost perfectly. The only oddity is that the AJAX generates additional '0 of 1 item selected' messages when previewing. Screenshot attached.

thetaPC’s picture

I'm also getting the weird message in Media Library as @R_H-L.

BinaryBlock’s picture

@DanielVeza and @nuez Obviously a lot has been happening in our lives and around the world as a whole.

I just wanted to see if either of you has been able to review the issues that have come forth and any ideas of how to resolve them?

My specific issue is outlined here: https://www.drupal.org/project/drupal/issues/2741877#comment-13577182

Thank you in advance and I totally understand if your attention has been needed elsewhere.

nuez’s picture

@BinaryBlock Thanks for your feedback. I can actually reproduce your error and it definitely needs to be addressed in this issue:

Maybe you can write a test to prove that this use case hasn't been solved in the patch of #48?

I also think that, even though we need to address this particular case described in #54, it's equally important that we get some reviews/guidance from a core maintainer or contributor to see if this is the right approach in the first place.

DanielVeza’s picture

Another thing this patch currently doesn't fix is Models with the same scope. This is an Edge case where we have a site that has a Thumbnail (Media library) field on a Remote Video Media Entity.

So:

  1. Inserting Media into the WYSWYG opens the first Media Library model.
  2. Uploading a new Remote Video works and opens the edit form correctly
  3. Trying to upload a new image to the Thumbnail field opens a new Media Library
  4. This replaces the original Media library model, which closes when you've finished, without uploading the video.
Rajab Natshah’s picture

Thank you
patch #48 is working
Create Blog post test - dev Varbase media library opening a modal from a modal closes the original

Version: 9.1.x-dev » 9.2.x-dev

Drupal 9.1.0-alpha1 will be released the week of October 19, 2020, which means new developments and disruptive changes should now be targeted for the 9.2.x-dev branch. For more information see the Drupal 9 minor version schedule and the Allowed changes during the Drupal 9 release cycle.

tanubansal’s picture

Tested #48 on 9.1, its working fine
This can be moved to RTBC

jastraat’s picture

Rerolled #48 for 9.2.x

jastraat’s picture

Sorry - corrected without the offsets from originally applying #48

The last submitted patch, 66: 2741877-nested_modals-66.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

Status: Needs review » Needs work

The last submitted patch, 67: 2741877-nested_modals-67.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

raman.b’s picture

Status: Needs work » Needs review
FileSize
17.04 KB
783 bytes
DanielVeza’s picture

Has #62 been tested with this patch?

Rar9’s picture

what patch to use with D9.0.8 with webform 6 alpha? #70 is not helping.

timodwhit’s picture

Thanks for the work @nuez.

Without bike shedding too much and as posted in #40, there are two issues at hand:
1) Core allowing nested modals
2) Places where modals break (ckeditor, media, etc)

Looking at the patch to allow the selector to specified, from the Close/Open Dialog this should be a quick patch that removes the hard coded reference. This is strictly copy and paste from @nuez' patch.

Once that patch is in, we could track the more complex interactions and bugs (media) have more comprehensive tests and issues that track other usability issues, where it needs to be enhanced, etc.

NOTE: the patch will not fix the media issues and will not solve the issues, it will just allow those issues to be solved future patches on separate items.

@wim @xjm, thoughts? This feels like an issue that will suffer a death by paper cuts if not segmented and focused.

markus_petrux’s picture

+1 for #73 approach, as this will also allow to resolve issues in custom code.

jastraat’s picture

Issue tags: +Media Initiative

Adding a Media Initiative tag.

daveiano’s picture

I got the same issue as described in #62

I have a media library field attached to a media entity (Media Type "File" has a field for a "Preview Image"). So if I want to set the file with media library, it opens the modal and I can upload a file. If I want to set the preview image, I am getting an ajax error:

Drupal\Core\Form\FormAjaxException: in Drupal\Core\Form\FormBuilder->buildForm() (Line 340 in /web/core/lib/Drupal/Core/Form/FormBuilder.php).

KapilV’s picture

Hear a reroll patch.

Nick Hope’s picture

Status: Needs review » Needs work

#77 applied fine for me to the current 9.2.x-dev but there is still a problem when using with CKEditor and adding links. These were my test steps, which are similar to #54:

1. Set up embedding media with CKEditor.
2. Enable a 'Text (formatted)' field on the Media library form mode of Image Media type.
3. Create Basic page and switch to a Text format that has the "Insert from Media Library" on the CKEditor toolbar.
4. Click 'Insert from media library' button.
5. Browse...
6. Select image.
7. Add required Alternative text.
8. 'Save and select'. Image appears in media library, pre-selected. (unlike the problem in #54)
9. 'Insert selected'. Image appears embedded in CKEditor.
10. Repeat for another new image but this time insert a link in the 'text (formatted)' field using the CKEditor link button (I tried 'https://www.drupal.org' and a couple of other links).
11. When I click "Save" nothing happens. The dialog remains on screen.
12. When I dismiss the dialog by clicking "X" it returns directly to the 'Create Basic page' page and the media item did not get added.

Adding links still works correctly when adding image media directly at /media/add/image.

This is a very new test site with little added. No Editor Advanced Link or Linkit installed.

While I'm here I'll link this issue with the Entity Reference Tree Widget that I'm hoping might get resolved by a fix for this issue. #77 unfortunately does not help that case either.

Nick Hope’s picture

Patch #70 does not allow new media to be inserted by either "Save and select" > "Insert selected" or by "Save and insert". But it does accept a link before that failure, and that link is remembered.

Version: 9.2.x-dev » 9.3.x-dev

Drupal 9.2.0-alpha1 will be released the week of May 3, 2021, which means new developments and disruptive changes should now be targeted for the 9.3.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

vakulrai’s picture

@Nick Hope , looks like the problem is with the plugins refocusing to the editor if text or entity is left unselected. I have added a solution for the link plugin, it is working for the scenario you mentioned.

Please review.

Gauravvvv’s picture

Nick Hope’s picture

Status: Needs review » Needs work

Thanks. I tried patches #81 and #82 in both Drupal 9.1.8 and 9.3.0-dev. Unfortunately in all cases the problem I described in #78 still remains. They also don't help the case of an Entity Reference Tree widget (modal) launched from a Hierarchy Manager modal (which is the issue that brought me here).

Carlitus’s picture

Tested #77 and #82 with Drupal 9.2, with a modal node form using class ajax and data-dialog-type="modal". In this node i have a media field with media library widget.

It doesn't work, just after i select the media it closes the current modal (the media modal) and nothing more happens.

briantes’s picture

Tested latest patch on Drupal 9.2.1, It doesn't work. If you add a ckeditor field in a custom modal form, and open this form, when you clic on url button or image button, the form is fully closed. I have tested the other patchs, but none works.

timodwhit’s picture

I'd like to try and reiterate my point in #73. There are complexities tied with the approaches in testing vs the simple ability to add an id for the open action.

Is it okay to separate the tasks and the areas of concerns?

Version: 9.3.x-dev » 9.4.x-dev

Drupal 9.3.0-rc1 was released on November 26, 2021, which means new developments and disruptive changes should now be targeted for the 9.4.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

RandalV’s picture

Bumping this issue again.

Is there any further development on this? I still cannot launch a link modal from a ckeditor wysiwyg inside a modal, my use case:

- List of media references
- Click the 'pencil'-icon, this opens up the media edit form in a modal
- Attempt to add a link in the custom description field (with basic html or something on)
- The initial modal closes, and the other modal is unable to add the link to anything since the ckeditor field is gone.

I've tried the latest patches, and these sadly do not change this as @Nick Hope mentioned.

AJV009’s picture

Priority: Normal » Major

Could this be in priority? Because I see this as a major bug!

larowlan’s picture

@AJV009 can you expand on why you feel this is major

Per the issue priorities

Major bugs include those that:

  • Interfere with normal site visitors' use of the site (for example, content in the wrong language, or validation errors for regular form submissions), even if there is a workaround.
  • Trigger a PHP error through the user interface, but only under rare circumstances or affecting only a small percentage of all users, even if there is a workaround.
  • Render one feature unusable with no workaround.
  • Block contributed projects with no workaround.
  • Cause a significant admin- or developer-facing bug with no workaround.
  • Cause user input to be lost, but do not delete or corrupt existing data.
  • Cause test failures in environments not supported by the automated testing platform.

Does this fall into one of those categories? If so can you update the issue summary to expand on the impact.

Thanks!

AJV009’s picture

Re-rolled "2741877-48.patch" patch from https://www.drupal.org/project/drupal/issues/2741877#comment-13563283 #48 from this thread.

Tested and worked on Drupal 9.3.9

I clearly understand we have shifted our focus to a more reliable solution, but until that happens we need to have something.

My patch might look a bit fuzzy, because I re-rolled it in just few seconds I was SUPER late for something when I was re-rolling the patch on a DrupalPod instance!

Thanks @nuez

And yes @larowlan, I might be able to assume that the problem falls under one of these
- Render one feature unusable with no workaround.
- Cause user input to be lost, but do not delete or corrupt existing data.

We have a pretty simple code that adds ['use-ajax'] and 'data-dialog-type' => ['modal'] to certain contextual links.

Everything works fine until I open another modal such as a media entity edit dialog box, when it opens the previous modal closes automatically weird right? therefore when I click on insert in the media library dialog box it closes as expected BUT the data which I inserted just vanishes, I couldn't see the previous window through which we opened this media library dialog box. MAGIC!LOST!

This causes the use-ajax feature unusable when used with media library modal.
Not just use-ajax being unusable but the data which I uploaded goes missing as well.

I made my last comment before I thought of reapplying neuz #48 patch.
So sorry about changing that the priority without thinking much.
Reverting the change since we have a workaround for now.

AJV009’s picture

Priority: Major » Normal

Since we have a workaround now maybe it can go to Normal.
I am really sorry about causing the mess here.

larowlan’s picture

Priority: Normal » Major

Hey @AJV009 no mess at all. If there's user input lost, then it is definitely major

guptahemant’s picture

Issue summary: View changes

Updated the summary.

Version: 9.4.x-dev » 9.5.x-dev

Drupal 9.4.0-alpha1 was released on May 6, 2022, which means new developments and disruptive changes should now be targeted for the 9.5.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

No Sssweat’s picture

#91 patch not working for me when editing a media image, which opens modal. Then trying to add link (via ckeditor) to the image caption field, which opens the ckeditor's url modal. This closes the media modal and clicking save on the url doesn't do anything. Same issue #88 said.

Version: 9.5.x-dev » 10.1.x-dev

Drupal 9.5.0-beta2 and Drupal 10.0.0-beta2 were released on September 29, 2022, which means new developments and disruptive changes should now be targeted for the 10.1.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

tobiberlin’s picture

I want to bump this again. Same issue as described in the last comments (and described by me three years ago)

  • In a node with a Reference field to a media entity (image) I want to add a new image
  • Clicking on the "add new media" button opens the media library in a modal
  • Here I create a new media -> in the modal the media entity form is shown. Our media entity has a textfield "copyright" with CKEditor where we want to link the source of the copyright licence
  • Clicking on the link button of the CKEditor opens the link modal / seems to replace the modal of the media library / media entity form
  • When click "save" in the now open link modal nothing happens in the browser just an error in browser console: Uncaught TypeError: Cannot read properties of null (reading 'getRanges')

I really have no clue if this is an issue for the Media or CKEditor / Text Editor module.

tlo405’s picture

I'm still seeing an issue here regarding modals and ckeditor5. I've already mentioned this here but I figured it wouldn't hurt to add it here as well.

In ckeditor4 I have a custom plugin that inserts some html onto the page. When clicking the icon on the ckeditor toolbar, a modal pops up with a form. The values of those form fields end up being inserted into the html as attributes. One of those fields is a media field that opens up another modal in an entity browser. I am able to make a selection from that modal, and then submit the original form in the first modal with no issues. The html gets inserted right into the editor.

However, in ckeditor5, this functionality breaks. If I don't click the 'select media' button to open up that 2nd modal, the html gets inserted correctly when I submit the original form. However I can't get any html to appear in the editor once I click the 'select media' button and that 2nd modal opens. Even if I close the entity browser modal without making a selection, it still won't insert any html into the editor when I submit the original form. I see no errors in the console either. I've applied the patches above but no luck.

alphex’s picture

I can confirm patch 91 doesn't work.

This is on Drupal 9.5.5, but... hoping the patch carries backwards.

I have a media entity which takes vimeo URLs.

But the project needs to upload their own custom placeholder image, but we want to use media for that.

So media library opens a modal for the VIDEO entity type, then clicking the add media button for the place holder image, opens the 2nd modal.

Selecting the image sends you back to the node edit screen ... and, you lose the other work you did to build the video entity.

Gauravvvv’s picture

Updating attributions

Fabsgugu’s picture

FileSize
122.25 KB

Hello,
I noticed a bug like this, so I don't know if it's related to this issue or not, but when I have a field media in a Node that has a media field itself, when I try to add a media in the modale I have a 500 error in the logs.

To reproduce:
- Have activated the modules: Node, Media and Media Library (No Contrib module is involved, I reproduced this Bug on an instance without, I even deactivated CKeditor.)
- Create Media with a media field (and put media library in the formatter form)
- Create a Node which is linked to the media field created (and put media library in the formatter form and also put the field in the formatter of media library)
- Add a content of this Node then add a media on the media field, which allows to open the modal
- Once the modal is open, add media via the upload form, which then allows you to arrive on the modification page
- Click on add media
- Nothing is happening

I have warnings in logs :

Warning: count(): Parameter must be an array or an object that implements Countable in Drupal\media_library\Form\FileUploadForm->validateUploadElement() (line 211 of /var/lib/tugboat/stm/web/core/modules/media_library/src/Form/FileUploadForm.php)

Notice: Undefined index: fids in Drupal\media_library\Form\FileUploadForm->validateUploadElement() (line 211 of /var/lib/tugboat/stm/web/core/modules/media_library/src/Form/FileUploadForm.php)

And i have an error in the console (which I also have in the logs) :

bug

Version: 10.1.x-dev » 11.x-dev

Drupal core is moving towards using a “main” branch. As an interim step, a new 11.x branch has been opened, as Drupal.org infrastructure cannot currently fully support a branch named main. New developments and disruptive changes should now be targeted for the 11.x branch, which currently accepts only minor-version allowed changes. For more information, see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

bkosborne’s picture

Ran into this today and tested the workaround patch in #91. My test case is a media library widget, where the user uploads a new image media entity. The image entity bundle has a CKEditor-enabled text field. Before the patch, clicking the Link button in the CKE dialog closes the Media Library widget prematurely. After the patch, the link dialog opens on top of it as it should. However, it seems to cause other issues. After closing the link dialog and saving the entity, the "Save and Select" button doesn't close the Media Library dialog anymore.

R_H-L’s picture

With the widespread adoption of the HTML dialog element, this should become more a matter of modernizing modals. This element supports chaining dialogs, styling, form awareness, good accessibility, and a host of other benefits.

Simple example:

  <dialog id="first-dialog">
    <p>Greetings, one and all!</p>
    <button data-role="open-dialog" data-target="#second-dialog" onclick="document.querySelector(this.getAttribute('data-target')).showModal()">Show second dialog</button>
    <button data-role="close-dialog" onclick="closest('dialog').close()">Close</button>
  </dialog>
  <dialog id="second-dialog">
    <p>Surprise!</p>
    <button data-role="close-dialog" onclick="closest('dialog').close()">Close</button>
  </dialog>
  <button data-role="open-dialog" data-target="#first-dialog" onclick="document.querySelector(this.getAttribute('data-target')).showModal()">Show dialog</button>

Edit, looks lik ethere is already an issue for this: Issue #2158943

arnaud-brugnon’s picture

#91 can't be apply on 10.1.

Here's the new version

larowlan’s picture

Status: Needs work » Needs review

Reroll of #91 as reroll at #106 was reporting as a corrupt patch file using git apply

larowlan’s picture

D10.0 version for those who need it

larowlan’s picture

More work here to support multiple editor dialogs, the saveCallback was previously only a single function but needs to be a Map keyed by the dialog selector

nuez’s picture

larowlan’s picture

Fixed linting issues and regression with the 'Save and insert' button in media library (argument order mismatch)

smustgrave’s picture

Status: Needs review » Needs work
Issue tags: +Needs issue summary update

CC Failure.

Also can the proposed solution be updated to include what path was taken.

_utsavsharma’s picture

Rerolled the patch for 11.x as the patch was not getting applied.
Please review.

a.dmitriiev’s picture

Uploading patch for 10.1.2 in case someone needs to use the fix for stable version. The change from 11.x patch for this file core/misc/dialog/dialog.js didn't work, because it has already more changes.

a.dmitriiev’s picture

The previous patch had a typo core/modules/media_library/src/MediaLibraryEditorOpener.php:

--- a/core/modules/media_library/src/MediaLibraryEditorOpener.php
+++ b/core/modules/media_library/src/MediaLibraryEditorOpener.php
@@ -70,7 +70,7 @@ public function getSelectionResponse(MediaLibraryState $state, array $selected_i
         'data-entity-uuid' => $selected_media->uuid(),
       ],
     ];
-    $response->addCommand(new EditorDialogSave($values));
+   $$response->addCommand(new EditorDialogSave($values, '#modal-media-library'));
 
     return $response;
   }

double $$. This is fixed in the new one. This patch is only to use in the project, there is no need to review it or test it.

Rar9’s picture

2741877-10.1.5-115.patch not working with D10.1.16

a.dmitriiev’s picture

Re-rolling the patch for 10.1.6

_utsavsharma’s picture

Tried to fix failures in #118.

pcambra’s picture

FileSize
16.33 KB
16.23 KB

I think the re-rolls from #113 onward are not really working, here are a Drupal 10.1 patch and a Drupal 11 patch that are functional.

pcambra’s picture

Status: Needs work » Needs review
_utsavsharma’s picture

Fixed failures in #119.

smustgrave’s picture

Status: Needs review » Needs work

Still needs an issue summary update before reviews.

leymannx’s picture

leymannx’s picture

Hiding patch, it's the same as in #2741877-121: Nested modals don't work: opening a modal from a modal closes the original.

I should have checked first. 😭

dinazaur’s picture

Fixed a bug that was caused by dialogSettings.options property. It led to unexpected behavior on modals. Sometimes they missed actions, not opened at all.

nuez’s picture

The reroll from #123 seems to be missing a few things. Embedding media doesn't seem to work with this reroll.

I've literally rerolled the d10 patch from #119 and there are a few differences.