Problem/Motivation

I want to be able to add custom contexts based on the $entity. When rendering an entity in Full view mode, custom ContextProviders can pull the entity from the route. But, what if you are working with a view of entities in Teaser view mode? I don't see a way to inform a ContextProvider of the entity.

Steps to reproduce

Proposed resolution

Add a new hook like hook_layout_builder_local_context_alter(&$contexts, $entity, $display). I would add it to the method below. Layout Builder uses this method to define the contexts when rendering an entity's layout. It:

  1. receives $entity as a parameter
  2. generates contexts based on local data
  3. runs all the contexts from ContextProviders
// from .../core/modules/layout_builder/src/Entity/LayoutBuilderEntityViewDisplay.php

  /**
   * Gets the available contexts for a given entity.
   *
   * @param \Drupal\Core\Entity\FieldableEntityInterface $entity
   *   The entity.
   *
   * @return \Drupal\Core\Plugin\Context\ContextInterface[]
   *   An array of context objects for a given entity.
   */
  protected function getContextsForEntity(FieldableEntityInterface $entity) {
    $available_context_ids = array_keys($this->contextRepository()->getAvailableContexts());
    return [
      'view_mode' => new Context(ContextDefinition::create('string'), $this->getMode()),
      'entity' => EntityContext::fromEntity($entity),
      'display' => EntityContext::fromEntity($this),
    ] + $this->contextRepository()->getRuntimeContexts($available_context_ids);
  }

I can take a first pass at making the change. I'd appreciate some feedback first. Is there already a way to modify the local contexts that I just haven't thought of?

Remaining tasks

User interface changes

Introduced terminology

API changes

Data model changes

Release notes snippet

Comments

jasonsafro created an issue. See original summary.

jasonsafro’s picture

Issue summary: View changes
jasonsafro’s picture

Issue summary: View changes
quietone’s picture

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

In Drupal core changes are made on on 11.x (our main development branch) first, and are then back ported as needed according to the Core change policies. Also mentioned on the version section of the list of issue fields documentation.

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.