Error when first media item is deleted in field with media attachment outside of node edit

Created on 15 April 2025, about 1 month ago

Problem/Motivation

Steps to reproduce

Given a simple node type
With a field for attaching media too
And you Attach two media items to that field on a node
And you go delete the first media item in /admin/content/media
When you Edit the node
You get the following error:

Error: Call to a member function id() on null in insert_media_insert_variables() (line 135 of modules/contrib/insert/modules/insert_media/insert_media.module).

Proposed resolution

The insert_media.module function insert_media_insert_variables() makes the assumption that 0 is always available. It isn't. If you delete 0 elsewhere, only 1 will be available, but there are no sanity checks so the error flies!

Remaining tasks

User interface changes

API changes

Update insert_media_insert_variables() to iterate over all keys until it finds a numeric key and use that. If it doesn't fund any, well it does nothing and that's okay somehow too.

Data model changes

πŸ› Bug report
Status

Needs work

Version

3.0

Component

Code

Created by

πŸ‡ΊπŸ‡ΈUnited States jnicola

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

  • Issue created by @jnicola
  • πŸ‡ΊπŸ‡ΈUnited States jnicola

    Attached a patch that works for us. I recognize the better way to do it is a commit in a fork but... eh I couldn't be bothered and since nobody else seems to be having this problem it likely doesn't matter.

    Solution though was simple. Instead of assuming the key of 0 exists, just iterative over keys until you find the first numerical key, and run with that if you get it. Further improvements are likely possible, but this works and doesn't feel hacky to me.

  • πŸ‡ΊπŸ‡ΈUnited States jnicola

    Uploading patch with slight tweak after code review. Original code returned based on first item value, so now we just return on the first found media item versus assuming the first item is 0.

  • Thank you for the patch! Definitely an improvement that should be merged in. Just one note: Shouldn't the check whether actually processing inserting media be kept to prevent potential interference with other hooks, and abort processing the hook early if not relevant for the current operation? Just adding an early return:

    function insert_media_insert_variables($insertType, array &$element, $styleName, &$vars) {
      if ($insertType !== INSERT_TYPE_MEDIA) {
        return;
      }
    
      foreach ($element['selection'] as $key => $val) {
        if (is_int($key)) {
          $vars['media_entity'] = $element['selection'][$key]['rendered_entity']['#media'];
          $mid = !is_null($vars['media_entity']) ? $vars['media_entity']->id() : 0;
          $element['#name'] = 'media_ ' . $mid;
          return;
        }
      }
    }
    
Production build 0.71.5 2024