Allow mgv plugins to be context-aware

Created on 27 May 2024, 29 days ago

Problem/Motivation

We have a use case for making a context-aware @Mgv plugin, like the following, which shows the title of the "current" node.

/**
 * @Mgv(
 *   id = "current_node_title",
 *   context_definitions = {
 *     "node" = @ContextDefinition("entity:node", label = @Translation("Node"), required = FALSE),
 *   },
 * );
 */
class CurrentNodeTitle extends GlobalVariable implements ContextAwarePluginInterface {
  public function getValue(): string {
    $node = $this->getContextValue('node');
    ...
  }

  // MGV plugins aren't configurable, so we hardcode the mapping here.
  // In this case we always want the "Node from URL" context value.
  public function getContextMapping() {
    return [
      'node' => '@node.node_route_context:node',
    ];
  }

}

At the moment this is impossible because MgvPluginManager does not anticipate @Mgv plugins being context-aware, and doesn't pass the necessary values to them.

Steps to reproduce

Try something like the above. $node will always be NULL.

Proposed resolution

Add the following to MgvPluginManager::getVariables(): (based on what BlockViewBuilder does for block plugins)

  if ($variable instanceof ContextAwarePluginInterface) {
    $contexts = \Drupal::service('context.repository')->getRuntimeContexts($variable->getContextMapping());
    \Drupal::service('context.handler')->applyContextMapping($variable, $contexts);
  }

Remaining tasks

Patch, test, get feedback.

User interface changes

None.

API changes

None. Existing plugins are unaffected.

Data model changes

None.

✨ Feature request
Status

Needs review

Version

2.2

Component

Code

Created by

πŸ‡ΈπŸ‡ͺSweden erik.erskine

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

Comments & Activities

Production build 0.69.0 2024