Persistent Null Reference Error in Block Content Entities Following Update from Core 10.2.4 to 10.2.5 or 10.2.6

Created on 6 May 2024, about 2 months ago
Updated 6 June 2024, 20 days ago

Problem/Motivation

I am experiencing an issue with my Drupal installation after updating from version 10.2.4 to 10.2.6. The update has led to an unexpected error related to block content entities, specifically causing a PHP error indicating a call to a member function on a null object within the block content plugin system.

Steps to reproduce

  • Start with a Drupal environment running version 10.2.4.
  • Perform an update to Drupal core version 10.2.6.
  • After the update, the error appears on all pages for both anonymous and authenticated users.
  • Proposed resolution

    I expected the site to function without interruption, with all block content loading as configured prior to the update.

    Actual Behavior

    Instead, the site presented an error message: "The website encountered an unexpected error. Try again later." More specifically, a PHP error was logged: "Error: Call to a member function label() on null in Drupal\block_content\Plugin\Derivative\BlockContent->getDerivativeDefinitions()". This error occurs when trying to interact with block content entities, suggesting an issue in their loading or initialization post-update.

    Environment Details

    • Drupal version : 10.2.6
    • DB driver : mysql
    • Database : Connected
    • Drupal bootstrap : Successful
    • Admin theme : seven
    • PHP binary : /usr/local/php8.1/bin/php
    • PHP config : /usr/local/php8.1/etc/cli/php.ini
    • PHP OS : Linux
    • PHP version : 8.1.24
    • Drush script : /var/www/html/vendor/bin/drush
    • Drush version : 12.4.3.0
    • Drush temp : /tmp
    • Drush configs : /etc/drush/drush.yml
    • /var/www/html/vendor/drush/drush/drush.yml

    • Install profile : standard
    • Drupal root : /var/www/html/docroot

    Proposed resolution

    I am seeking assistance from the Drupal community to help debug this issue. My installation runs smoothly on Drupal core version 10.2.4 without any errors. However, when I update to either Drupal core 10.2.5 or 10.2.6, the error appears. This suggests that there may be changes introduced in these later versions that affect block content handling in my specific setup. I would appreciate any insights or recommendations on troubleshooting steps that could help identify and resolve the underlying cause of this error. Collaboration on developing a patch or identifying a workaround to ensure compatibility with these core versions would also be invaluable.

    User interface changes

    No changes to the user interface are proposed;

    API changes

    No changes to APIs are expected ./p>

    Data model changes

    No data model changes are proposed.

    πŸ› Bug report
    Status

    Postponed: needs info

    Version

    11.0 πŸ”₯

    Component
    Block contentΒ  β†’

    Last updated 5 days ago

    Created by

    πŸ‡ΊπŸ‡ΈUnited States mario.elias

    Live updates comments and jobs are added and updated live.
    • Needs tests

      The change is currently missing an automated test that fails when run with the original code, and succeeds when the bug has been fixed.

    Sign in to follow issues

    Comments & Activities

    • Issue created by @mario.elias
    • πŸ‡ΊπŸ‡ΈUnited States cilefen

      For general debugging, here are a series of steps to take that increase in complexity. Start at the first step then continue if you can't solve it there.

      1. Post the complete error message here, including line numbers.
      2. Post the stack trace here. Sometimes that alone points to the cause.
      3. Use a PHP debugger like Xdebug to stop execution in the function that throws the exception. Examine the call stack and values.
      4. Execute `git bisect` on Drupal Core to identify the commit that changed behavior.
    • πŸ‡ΊπŸ‡ΈUnited States mario.elias

      I am adding complete error message here, including line numbers. Thank you @cilefen for your feedback.
      The website encountered an unexpected error. Try again later.

      Error: Call to a member function label() on null in Drupal\block_content\Plugin\Derivative\BlockContent->getDerivativeDefinitions() (line 52 of core/modules/block_content/src/Plugin/Derivative/BlockContent.php).
      Drupal\Component\Plugin\Discovery\DerivativeDiscoveryDecorator->getDerivatives(Array) (Line: 87)
      Drupal\Component\Plugin\Discovery\DerivativeDiscoveryDecorator->getDefinitions() (Line: 323)
      Drupal\Core\Plugin\DefaultPluginManager->findDefinitions() (Line: 205)
      Drupal\Core\Plugin\DefaultPluginManager->getDefinitions() (Line: 22)
      Drupal\Core\Plugin\DefaultPluginManager->getDefinition('block_content:2f516acc-dd9d-44cf-b764-ac9c80821252') (Line: 16)
      Drupal\Core\Plugin\Factory\ContainerFactory->createInstance('block_content:2f516acc-dd9d-44cf-b764-ac9c80821252', Array) (Line: 76)
      Drupal\Component\Plugin\PluginManagerBase->createInstance('block_content:2f516acc-dd9d-44cf-b764-ac9c80821252', Array) (Line: 62)
      Drupal\Core\Plugin\DefaultSingleLazyPluginCollection->initializePlugin('block_content:2f516acc-dd9d-44cf-b764-ac9c80821252') (Line: 57)
      Drupal\block\BlockPluginCollection->initializePlugin('block_content:2f516acc-dd9d-44cf-b764-ac9c80821252') (Line: 80)
      Drupal\Component\Plugin\LazyPluginCollection->get('block_content:2f516acc-dd9d-44cf-b764-ac9c80821252') (Line: 45)
      Drupal\block\BlockPluginCollection->get('block_content:2f516acc-dd9d-44cf-b764-ac9c80821252') (Line: 83)
      Drupal\Core\Plugin\DefaultSingleLazyPluginCollection->setConfiguration(Array) (Line: 99)
      Drupal\Core\Plugin\DefaultSingleLazyPluginCollection->addInstanceId('block_content:2f516acc-dd9d-44cf-b764-ac9c80821252', Array) (Line: 55)
      Drupal\Core\Plugin\DefaultSingleLazyPluginCollection->__construct(Object, 'block_content:2f516acc-dd9d-44cf-b764-ac9c80821252', Array) (Line: 34)
      Drupal\block\BlockPluginCollection->__construct(Object, 'block_content:2f516acc-dd9d-44cf-b764-ac9c80821252', Array, 'aboutusmenuheader') (Line: 156)
      Drupal\block\Entity\Block->getPluginCollection() (Line: 145)
      Drupal\block\Entity\Block->getPlugin() (Line: 118)
      Drupal\block\BlockAccessControlHandler->checkAccess(Object, 'view', Object) (Line: 109)
      Drupal\Core\Entity\EntityAccessControlHandler->access(Object, 'view', Object, 1) (Line: 329)
      Drupal\Core\Entity\EntityBase->access('view', NULL, 1) (Line: 63)
      Drupal\block\BlockRepository->getVisibleBlocksPerRegion(Array) (Line: 137)
      Drupal\block\Plugin\DisplayVariant\BlockPageVariant->build() (Line: 270)
      Drupal\Core\Render\MainContent\HtmlRenderer->prepare(Array, Object, Object) (Line: 128)
      Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object, Object) (Line: 90)
      Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object, 'kernel.view', Object)
      call_user_func(Array, Object, 'kernel.view', Object) (Line: 111)
      Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch(Object, 'kernel.view') (Line: 186)
      Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 76)
      Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 58)
      Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 48)
      Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 28)
      Drupal\Core\StackMiddleware\ContentLength->handle(Object, 1, 1) (Line: 106)
      Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 85)
      Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 53)
      Asm89\Stack\Cors->handle(Object, 1, 1) (Line: 50)
      Drupal\ban\BanMiddleware->handle(Object, 1, 1) (Line: 48)
      Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 51)
      Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 36)
      Drupal\Core\StackMiddleware\AjaxPageState->handle(Object, 1, 1) (Line: 51)
      Drupal\Core\StackMiddleware\StackedHttpKernel->handle(Object, 1, 1) (Line: 704)
      Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

    • πŸ‡ΊπŸ‡ΈUnited States analaura@cellar-door.io Houston, TX
    • πŸ‡ΊπŸ‡ΈUnited States mario.elias

      I found additional information regarding the error while traced through our server logs.

      Error Log Entry:

      WARNING: [pool www] child 7000 said into stderr: "NOTICE: PHP message: Uncaught PHP Exception Error: "Call to a member function label() on null" at /var/www/html/docroot/core/modules/block_content/src/Plugin/Derivative/BlockContent.php line 52"
      2024/05/08 15:42:46 [error] 2069#2069: *227 FastCGI sent in stderr: "PHP message: Uncaught PHP Exception Error: "Call to a member function label() on null" at /var/www/html/docroot/core/modules/block_content/src/Plugin/Derivative/BlockContent.php line 52" while reading response header from upstream, client: 172.18.0.5, server: , request: "GET / HTTP/1.1", upstream: "fastcgi://unix:/run/php-fpm.sock:", host: "www.mydomain.com"

      Code Location:
      The error is consistently pointing to line 52 in /var/www/html/docroot/core/modules/block_content/src/Plugin/Derivative/BlockContent.php, where there seems to be a null object reference issue when attempting to access the label() function.

            1 <?php
            2 
            3 namespace Drupal\block_content\Plugin\Derivative;
            4 
            5 use Drupal\Component\Plugin\Derivative\DeriverBase;
            6 use Drupal\Core\Entity\EntityStorageInterface;
            7 use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
            8 use Symfony\Component\DependencyInjection\ContainerInterface;
            9 
           10 /**
           11  * Retrieves block plugin definitions for all content blocks.
           12  */
           13 class BlockContent extends DeriverBase implements ContainerDeriverInterface {
           14 
           15   /**
           16    * The content block storage.
           17    *
           18    * @var \Drupal\Core\Entity\EntityStorageInterface
           19    */
           20   protected $blockContentStorage;
           21 
           22   /**
           23    * Constructs a BlockContent object.
           24    *
           25    * @param \Drupal\Core\Entity\EntityStorageInterface $block_content_storage
           26    *   The content block storage.
           27    */
           28   public function __construct(EntityStorageInterface $block_content_storage) {
           29     $this->blockContentStorage = $block_content_storage;
           30   }
           31 
           32   /**
           33    * {@inheritdoc}
           34    */
           35   public static function create(ContainerInterface $container, $base_plugin_id) {
           36     $entity_type_manager = $container->get('entity_type.manager');
           37     return new static(
           38       $entity_type_manager->getStorage('block_content')
           39     );
           40   }
           41 
           42   /**
           43    * {@inheritdoc}
           44    */
           45   public function getDerivativeDefinitions($base_plugin_definition) {
           46     $block_contents = $this->blockContentStorage->loadByProperties(['reusable' => TRUE]);
           47     // Reset the discovered definitions.
           48     $this->derivatives = [];
           49     /** @var \Drupal\block_content\Entity\BlockContent $block_content */
           50     foreach ($block_contents as $block_content) {
           51       $this->derivatives[$block_content->uuid()] = $base_plugin_definition;
           52       $this->derivatives[$block_content->uuid()]['admin_label'] = $block_content->label() ?? ($block_content->type->entity->label() . ': ' . $block_cont     52 ent->id());
           53       $this->derivatives[$block_content->uuid()]['config_dependencies']['content'] = [
           54         $block_content->getConfigDependencyName(),
           55       ];
           56     }
           57     return parent::getDerivativeDefinitions($base_plugin_definition);
           58   }
           59 
           60 }
      
    • πŸ‡ΊπŸ‡ΈUnited States mario.elias

      I would like to propose changes to the BlockContent.php file within the block_content module to handle potential null entity issues that have been causing errors in our environment.

      Issue Description:
      We have encountered a recurring error when the label() function is called on a null block_content entity. This results in a PHP exception "Call to a member function label() on null."

      Proposed Changes:
      To address this issue, I've implemented a null check before accessing the block_content entity's methods. Below is the diff of the changes made:

      diff --git a/docroot/core/modules/block_content/src/Plugin/Derivative/BlockContent.php b/docroot/core/modules/block_content/src/Plugin/Derivative/BlockContent.php
      index 5ba836f1a8..73a99af376 100644
      --- a/docroot/core/modules/block_content/src/Plugin/Derivative/BlockContent.php
      +++ b/docroot/core/modules/block_content/src/Plugin/Derivative/BlockContent.php
      @@ -48,13 +48,19 @@ public function getDerivativeDefinitions($base_plugin_definition) {
           $this->derivatives = [];
           /** @var \Drupal\block_content\Entity\BlockContent $block_content */
           foreach ($block_contents as $block_content) {
      -      $this->derivatives[$block_content->uuid()] = $base_plugin_definition;
      -      $this->derivatives[$block_content->uuid()]['admin_label'] = $block_content->label();
      -      $this->derivatives[$block_content->uuid()]['config_dependencies']['content'] = [
      -        $block_content->getConfigDependencyName(),
      -      ];
      +      if ($block_content !== null) {
      +        $uuid = $block_content->uuid();
      +        $this->derivatives[$uuid] = $base_plugin_definition;
      +        // Use null coalescing operator to safely attempt to call label()
      +        $this->derivatives[$uuid]['admin_label'] = $block_content->label() ?? 'Default Label';
      +        $this->derivatives[$uuid]['config_dependencies']['content'] = [
      +          $block_content->getConfigDependencyName(),
      +        ];
      +      } else {
      +        // Optionally log or handle the case when block_content is unexpectedly null
      +        \Drupal::logger('block_content')->warning('Encountered a null block content entity.');
      +      }
           }
           return parent::getDerivativeDefinitions($base_plugin_definition);
         }
      -
       }
      

      I am looking forward a feedback on this patch. If deemed suitable, I would appreciate guidance on the formal submission process for these changes to the Drupal community.

      Thank you for your attention and support.

      Mario

    • Status changed to Postponed: needs info about 2 months ago
    • πŸ‡ΊπŸ‡ΈUnited States cilefen

      This is a bug report that needs steps to reproduce. Why is the value null?

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

      Also: the way to propose changes is with a pull request.

    • Status changed to Needs review about 2 months ago
    • πŸ‡ΊπŸ‡ΈUnited States mario.elias

      I have created and attached a patch that addresses the null reference error in BlockContent.php. I have thoroughly tested it in my environment, and it resolves the issue effectively.

      Please find the patch attached for review. I welcome any feedback or additional testing from the community to ensure the change meets all necessary criteria and does not introduce any regressions.

      Thank you for reviewing this patch.

    • Status changed to Needs work about 2 months ago
    • πŸ‡¦πŸ‡ΊAustralia acbramley

      That line has 2 calls to ->label() it would be good to know which one is throwing the error. I.e is loadByProperties() returning NULL, or is $block_content->type->entity returning NULL.

      If it's the former then that's a larger issue, if it's the latter then it means the block content type for your block no longer exists which is an issue with your site.

      We need steps to reproduce from a fresh installation. The current steps are not sufficient to reproduce the bug.

    • Status changed to Postponed: needs info 20 days ago
    • πŸ‡¦πŸ‡ΊAustralia acbramley

      Should be PMNMI

    Production build 0.69.0 2024