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:
- receives $entity as a parameter
- generates contexts based on local data
- 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?
Comments
Comment #2
jasonsafro commentedComment #3
jasonsafro commentedComment #4
quietone commentedIn 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.