Problem/Motivation

This error occurs when we click on 'Insert Selected' button from the media library without selecting or uploading a media.

Steps to reproduce

  • Go to any add/edit node page with body field.
  • Click on the media library button from the CKeditor
  • Click on the 'Insert Media' button from the image media type tab

It won't show any error in the frontend but logs an error message in watchdog and in browser console.
We see the 'No items selected' message only after switching media tabs.

Proposed resolution

  1. Prepare the form validate method to the case when there aren't any items selected.
  2. Display messages if the form has any error.

Remaining tasks

  1. Patch ✅
  2. Test coverage
  3. Approval of core maintainer(s).

User interface changes

When the Media Library form is submitted without any selected media items, an error message appears on the form.

API changes

Nothing.

Data model changes

Nothing.

Release notes snippet

Not needed as this is a bug?..

Issue fork drupal-3303889

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

srijeeta created an issue. See original summary.

srijeeta’s picture

Issue summary: View changes
srijeeta’s picture

srijeeta’s picture

cilefen’s picture

Issue tags: -media library, -media widget

Is there additional setup or can this be reproduced by installing Drupal?

Please post stack traces as code rather than as an image.

srijeeta’s picture

No additional setup, just installing Drupal will be fine.

Post stack trace:

Error: Call to a member function uuid() on null in Drupal\media_library\MediaLibraryEditorOpener->getSelectionResponse() (line 72 of /app/docroot/core/modules/media_library/src/MediaLibraryEditorOpener.php)
#0 /app/docroot/core/modules/media_library/src/Plugin/views/field/MediaLibrarySelectForm.php(140): Drupal\media_library\MediaLibraryEditorOpener->getSelectionResponse(Object(Drupal\media_library\MediaLibraryState), Array)
#1 [internal function]: Drupal\media_library\Plugin\views\field\MediaLibrarySelectForm::updateWidget(Array, Object(Drupal\Core\Form\FormState), Object(Symfony\Component\HttpFoundation\Request))
#2 /app/docroot/core/lib/Drupal/Core/Form/FormAjaxResponseBuilder.php(69): call_user_func_array(Array, Array)
#3 /app/docroot/core/lib/Drupal/Core/Form/EventSubscriber/FormAjaxSubscriber.php(109): Drupal\Core\Form\FormAjaxResponseBuilder->buildResponse(Object(Symfony\Component\HttpFoundation\Request), Array, Object(Drupal\Core\Form\FormState), Array)
#4 [internal function]: Drupal\Core\Form\EventSubscriber\FormAjaxSubscriber->onException(Object(Symfony\Component\HttpKernel\Event\ExceptionEvent), 'kernel.exceptio...', Object(Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher))
#5 /app/docroot/core/lib/Drupal/Component/EventDispatcher/ContainerAwareEventDispatcher.php(142): call_user_func(Array, Object(Symfony\Component\HttpKernel\Event\ExceptionEvent), 'kernel.exceptio...', Object(Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher))
#6 /app/vendor/symfony/http-kernel/HttpKernel.php(219): Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch(Object(Symfony\Component\HttpKernel\Event\ExceptionEvent), 'kernel.exceptio...')
#7 /app/vendor/symfony/http-kernel/HttpKernel.php(91): Symfony\Component\HttpKernel\HttpKernel->handleThrowable(Object(Drupal\Core\Form\FormAjaxException), Object(Symfony\Component\HttpFoundation\Request), 1)
#8 /app/docroot/core/lib/Drupal/Core/StackMiddleware/Session.php(58): Symfony\Component\HttpKernel\HttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#9 /app/docroot/core/lib/Drupal/Core/StackMiddleware/KernelPreHandle.php(48): Drupal\Core\StackMiddleware\Session->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#10 /app/docroot/core/modules/page_cache/src/StackMiddleware/PageCache.php(106): Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#11 /app/docroot/core/modules/page_cache/src/StackMiddleware/PageCache.php(85): Drupal\page_cache\StackMiddleware\PageCache->pass(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#12 /app/docroot/modules/contrib/shield/src/ShieldMiddleware.php(265): Drupal\page_cache\StackMiddleware\PageCache->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#13 /app/docroot/modules/contrib/shield/src/ShieldMiddleware.php(221): Drupal\shield\ShieldMiddleware->bypass(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#14 /app/docroot/core/lib/Drupal/Core/StackMiddleware/ReverseProxyMiddleware.php(48): Drupal\shield\ShieldMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#15 /app/docroot/core/lib/Drupal/Core/StackMiddleware/NegotiationMiddleware.php(51): Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#16 /app/vendor/stack/builder/src/Stack/StackedHttpKernel.php(23): Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#17 /app/docroot/core/lib/Drupal/Core/DrupalKernel.php(709): Stack\StackedHttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#18 /app/docroot/index.php(19): Drupal\Core\DrupalKernel->handle(Object(Symfony\Component\HttpFoundation\Request))
#19 {main}

jaykumar95’s picture

this error also occurred in 9.4.x and 10.0.x

aarti zikre’s picture

StatusFileSize
new51.54 KB
new23.7 KB
new23.63 KB

not able to produce the issue.

Testing steps:
1. Created new instance of drupal 9.5.x
2. enable media and media library module
3. configure it in ckeditor basic html /admin/config/content/formats.
4. created new basic page.
5. click on Insert media from library.
6. choose audio tab and inserted one audio.

able to save and see the audio on front end without any error while save and in WD.
performed this same for image too.
Attaching SS for reference.

jaykumar95’s picture

we need to make some changes on below files.
1.web\core\modules\media_library\src\Plugin\views\field\MediaLibrarySelectForm.php

$selected = array_filter($form_state->getValue($this->options['id']));
    if (empty($selected)) {
      $form_state->setErrorByName('', $this->t('No items selected.'));
    }

to

$selected = array_filter($form_state->getValue($this->options['id']) ?? []);
    if (empty($selected)) {
      $form_state->setErrorByName('', $this->t('No items selected.'));
    }

as we have not selected any item from the list $this->options['id'] is always be null
2. web\core\modules\media_library\src\MediaLibraryEditorOpener.php

public function getSelectionResponse(MediaLibraryState $state, array $selected_ids) {
    $selected_media = $this->mediaStorage->load(reset($selected_ids));

    $response = new AjaxResponse();
    $values = [
      'attributes' => [
        'data-entity-type' => 'media',
        'data-entity-uuid' => $selected_media->uuid(),
        'data-align' => 'center',
      ],
    ];
    $response->addCommand(new EditorDialogSave($values));

    return $response;
  }

to

$selected_media = $this->mediaStorage->load(reset($selected_ids));
    $response = new AjaxResponse();
    if (isset($selected_media)) {
      $values = [
        'attributes' => [
          'data-entity-type' => 'media',
          'data-entity-uuid' => $selected_media->uuid(),
          'data-align' => 'center',
        ],
      ];
      $response->addCommand(new EditorDialogSave($values));
    } else {
      $response->addCommand(new MessageCommand($this->t('No items selected.')));
    }
    return $response;
jaykumar95’s picture

after applying above changes I am getting below warning in response

( ! ) Warning: array_flip(): Can only flip string and integer values, entry skipped in \drupal-nine\web\core\lib\Drupal\Core\Entity\EntityStorageBase.php on line 312

pointing to this line

$flipped_ids = $ids ? array_flip($ids) : FALSE;

jaykumar95’s picture

have fixed it by adding array_filter on it as there is no item selected from the list.

$flipped_ids = $ids ? array_flip(array_filter($ids)) : FALSE;

cilefen’s picture

@ aarti zikre I think the steps to reproduce are different. Can you verify?

jaykumar95’s picture

@ aarti zikre @cilfen
the 6th step is click on Insert selected button without choosing any items.

jaykumar95’s picture

#11 throwing error on content view page, need to check other way to fix

jaykumar95’s picture

found the fix.
we need to check the $selected_ids in response;
change in file web\core\modules\media_library\src\MediaLibraryEditorOpener.php would be

public function getSelectionResponse(MediaLibraryState $state, array $selected_ids) {
    $response = new AjaxResponse();
    if (!empty($selected_ids)) {
      $selected_media = $this->mediaStorage->load(reset($selected_ids));
      $values = [
        'attributes' => [
          'data-entity-type' => 'media',
          'data-entity-uuid' => $selected_media->uuid(),
          'data-align' => 'center',
        ],
      ];
      $response->addCommand(new EditorDialogSave($values));
    } else {
      $response->addCommand(new MessageCommand($this->t('No items selected.')));
    }
    return $response;
  }
srijeeta’s picture

@JayKumar95 I checked with your fix mentioned, few changes:

  • MessageCommand class needs to be added, but that can be added while creating a patch
  • $this->t() function in MediaLibraryEditorOpener file was giving this error: Error: Call to undefined method Drupal\media_library\MediaLibraryEditorOpener::t() in Drupal\media_library\MediaLibraryEditorOpener->getSelectionResponse() (line 92 of /app/docroot/core/modules/media_library/src/MediaLibraryEditorOpener.php), so I changed it t() and it worked.

Currently the behaviour is if we click on Insert Selected without choosing any media, the modal closes and then when we open it back again it shows a message 'No items selected'.

jaykumar95’s picture

yes @srijeeta the class will be added in patch. for t() we can use the StringTranslationTrait.

my query is do we need to show the status message or just silently close the dialog box, same as in views where we click on add field button without selecting any fields?

@srijeeta are you creating patch?

srijeeta’s picture

No @Jaykumar95, I didn't create a patch yet.

I'm also thinking the same thing, I feel like there should be a way to display the error message 'No items selected' on the button click.

jaykumar95’s picture

another workaround is to check the selected ids on updateWidget() function in web\core\modules\media_library\src\Plugin\views\field\MediaLibrarySelectForm.php.

I have updated code according to #16 & 18 to remove the duplicate status messages and only show once inside the dialog box.

use Drupal\Core\Ajax\RemoveCommand;
use Drupal\Core\Ajax\PrependCommand;

public static function updateWidget(array &$form, FormStateInterface $form_state, Request $request) {
    $field_id = $form_state->getTriggeringElement()['#field_id'];
    $selected_ids = $form_state->getValue($field_id);
    $selected_ids = $selected_ids ? array_filter(explode(',', $selected_ids)) : [];
    if (empty($selected_ids)) {
      $response = new AjaxResponse();
      $messages = ['#type' => 'status_messages'];
      $response->addCommand(new RemoveCommand('#media-library-add-form-wrapper [data-drupal-messages]'));
      $response->addCommand(new PrependCommand('#media-library-add-form-wrapper', \Drupal::service('renderer')->renderRoot($messages)));
      return $response;
    }
    // Allow the opener service to handle the selection.
    $state = MediaLibraryState::fromRequest($request);

    return \Drupal::service('media_library.opener_resolver')
      ->get($state)
      ->getSelectionResponse($state, $selected_ids)
      ->addCommand(new CloseDialogCommand());
  }
jaykumar95’s picture

Status: Active » Needs review
StatusFileSize
new1.46 KB

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.

jamesyao’s picture

Hello, I am having the same problem after the site was upgraded from Drupal Core 9.3.6 to 9.47. When the anonymous user tries to insert a media item in CKeditor, the error ((Call to a member function uuid() on null in Drupal\media_library\MediaLibraryEditorOpener)) occurs.

Thanks @Jaykumar95 for providing the patch #20. I applied the patch on the Drupal core 9.4.7 site. As a result, the error does not occur anymore, and the media still is not inserted into the CKeditor for the anonymous user. The the anonymous user role has the administer media permission.

Drupal environment:
Drupal Core 9.4.x
PHP 8.0

smustgrave’s picture

Status: Needs review » Needs work
Issue tags: +Needs tests, +Needs Review Queue Initiative, +Needs issue summary update

This issue is being reviewed by the kind folks in Slack, #need-reveiw-queue. We are working to keep the size of Needs Review queue [2700+ issues] to around 200, following Review a patch or merge require as a guide.

Attempted to replicate on 10.1 but could not.

Tagging for IS update as there is no proposed solution.

Tagging for tests as bug will need a test case that replicates the issue and causes the error.

Also not sure about the fix has it seems to be fixing a symptom vs root cause.

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.

balramchauhan684’s picture

balramchauhan684’s picture

StatusFileSize
new1.5 KB
gaele’s picture

Status: Needs work » Needs review
smustgrave’s picture

Status: Needs review » Needs work

Still needs a test case.

Typically with these type of issues just putting an isset() or empty() check is masking a deeper issue that should be determined.

larskleiner’s picture

larskleiner’s picture

alvarito75’s picture

I have the same issue.

This is my setup:

  • Drupal 10.1.3
  • PHP 8.1.14
  • MariaDB: 10.4.22-MariaDB-1:10.4.22+maria~focal
  • Admin theme is Gin
  • CKEditor5

By the way, patch #30 is already included in this Drupal version. And I'm upgrading from CKEditor 4 to CKEditor 5.

xjkwak’s picture

I was able to reproduce the issue only with Twig Debug enabled.

ion.macaria’s picture

Reroll patch for drupal 10.1.7.

ion.macaria’s picture

StatusFileSize
new1.48 KB

Fix missed used statements. Drupal 10.1.7

zeeshan_khan’s picture

@ion.macaria - Can you provide interdiff from #30 as it looks same to me.
Also we still need test case for this as mentioned by @smustgrave in #23
Also we need to update the code as suggested in #28 by @smustgrave I agree that using empty() check in this kind situation can cause deeper problems.

joseph.olstad’s picture

patch #34 applies cleanly to Drupal 10.2.3 and fixes the bug.
Needed this after an upgrade from 10.0.11

herved’s picture

This seems to relate/overlap with #3340973: Media Library: Argument #1 ($array) must be of type array, null given in array_filter()..
The MR there seems to fix it but I haven't compared the code of both solutions yet.

samit.310@gmail.com made their first commit to this issue’s fork.

samitk’s picture

Status: Needs work » Needs review
Related issues: +#3351597: [random test failure] Drupal\Tests\ckeditor5\FunctionalJavascript\MediaLibraryTest
StatusFileSize
new867.96 KB

Hi, I have created the MR, I also added an extra condition in viewsFormValidate that fixed following error(Also added the screenshot).

TypeError: array_filter(): Argument #1 ($array) must be of type array, null given in array_filter() (line 185 of /var/www/html/core/modules/media_library/src/Plugin/views/field/MediaLibrarySelectForm.php).

Test case is still pending, Post observing core/modules/ckeditor5/tests/src/FunctionalJavascript/MediaLibraryTest.php it seems not compatible with Drupal 11 as it still using create blog content permission.

One related issue is https://www.drupal.org/project/drupal/issues/3351597

Thanks
Samit K.

smustgrave’s picture

Status: Needs review » Needs work

Previously tagged for tests and issue summary both appear still needed.

mortona2k’s picture

I ran into this error, but replacing my site config with the default media library view fixed it.

I had changed the view display to use responsive grid.

But that display doesn't support row classes, relating to https://www.drupal.org/project/drupal/issues/2474491

I made a custom display that extends responsive grid to add custom classes back in, and it's working again.

bingol@ciandt.com’s picture

StatusFileSize
new1.49 KB

Version: 11.x-dev » main

Drupal core is now using the main branch as the primary development branch. New developments and disruptive changes should now be targeted to the main branch.

Read more in the announcement.

zeeshan_khan’s picture

StatusFileSize
new7.72 KB

This patch addresses the fatal error "Call to a member function uuid() on null" that occurs when clicking "Insert Selected" in the Media Library without selecting any media items.

Changes

MediaLibrarySelectForm.php
Added early validation in `updateWidget()` to check for empty selection and return a user-friendly error message:

```php
if (empty($selected_ids)) {
$response = new AjaxResponse();
$response->addCommand(new MessageCommand(
(string) \Drupal::translation()->translate('No media items were selected.'),
'#media-library-messages',
['type' => 'error']
));
return $response;
}
```

MediaLibraryEditorOpener.php (NEW - not covered by existing MR)
Added defensive null checks in `getSelectionResponse()` to prevent crashes even if validation is bypassed:

```php
// Return empty response if no media items were selected.
if (empty($selected_ids)) {
return $response;
}

$selected_media = $this->mediaStorage->load(reset($selected_ids));

// Return empty response if the media entity could not be loaded.
if (!$selected_media) {
return $response;
}
```

This defensive fix is important because:
- It prevents crashes if `getSelectionResponse()` is called directly (e.g., by custom code)
- It handles the edge case where a media entity is deleted between selection and submission
- It follows defensive programming best practices

Test Coverage
Added new kernel test `MediaLibraryEditorOpenerTest.php` with three test methods:
- `testGetSelectionResponseWithEmptySelection()` - Verifies empty array doesn't crash
- `testGetSelectionResponseWithInvalidMediaId()` - Verifies non-existent media ID doesn't crash
- `testGetSelectionResponseWithValidSelection()` - Verifies normal operation still works

How to Test Manually

1. Apply the patch
2. Go to any CKEditor field with media embed enabled
3. Click the media button to open Media Library
4. Without selecting any media, click "Insert Selected"
5. **Before patch**: Fatal error
6. **After patch**: Error message "No media items were selected."

Difference from Existing MR (!9413)

The existing MR adds validation in `updateWidget()` but does **not** add defensive checks to `MediaLibraryEditorOpener::getSelectionResponse()`. This patch includes both:

1. Form-level validation (similar to MR approach but simpler)
2. Opener-level defensive checks (not in MR)

The defensive checks in the opener are valuable because they protect against:
- Direct calls to `getSelectionResponse()` that bypass form validation
- Race conditions where media is deleted between selection and submission
- Any future code paths that might call the opener directly

zeeshan_khan’s picture

Status: Needs work » Needs review
smustgrave’s picture

Status: Needs review » Needs work

Thanks but tests need to be added to the MR to show it's fixing the problem. patches don't run the test suite. Also issue summary still needs to be updated.

alorenc made their first commit to this issue’s fork.

huzooka’s picture

Assigned: Unassigned » huzooka
huzooka’s picture

Issue tags: -Needs tests

From now on, we have a test in MR 9413.

huzooka’s picture

Issue summary: View changes
Issue tags: -Needs issue summary update

Issue summary must be better now.

huzooka’s picture

Assigned: huzooka » Unassigned
Status: Needs work » Needs review
dimilias’s picture

Status: Needs review » Reviewed & tested by the community

I tested the test with and without the fix.
Namely:

ddev exec ./vendor/bin/phpunit -c core core/modules/media_library/tests/src/FunctionalJavascript/EmbeddedFormWidgetTest
git revert d500fff685089e062f505a3f64b8a20f7ff48111
ddev exec ./vendor/bin/phpunit -c core core/modules/media_library/tests/src/FunctionalJavascript/EmbeddedFormWidgetTest

First one passed
Second one failed.

I did not perform a QA in the code as, from the comments, I see that the tests were missing. RTBC +1.

quietone’s picture

Status: Reviewed & tested by the community » Needs work
Issue tags: +Needs title update

There are comments in the MR to address.

The title should be description of the change, so adding tag.

sivaji_ganesh_jojodae’s picture

Title: Error: Call to a member function uuid() on null in Drupal\media_library\MediaLibraryEditorOpener->getSelectionResponse() (line 72 of /app/docroot/core/modules/media_library/src/MediaLibraryEditorOpener.php) » Media Library: Clicking "Insert selected" with no media selected triggers fatal error
arunkumark’s picture

Verified the patch is working fine in the Drupal 10.x version. Sharing the verification in local.

Video

Still the Comments need to be addressed.