3 namespace Drupal\Core\Plugin;
6 * Handles context assignments for context-aware plugins.
8 trait ContextAwarePluginAssignmentTrait {
11 * Ensures the t() method is available.
13 * @see \Drupal\Core\StringTranslation\StringTranslationTrait
15 abstract protected function t($string, array $args = [], array $options = []);
18 * Wraps the context handler.
20 * @return \Drupal\Core\Plugin\Context\ContextHandlerInterface
22 protected function contextHandler() {
23 return \Drupal::service('context.handler');
27 * Builds a form element for assigning a context to a given slot.
29 * @param \Drupal\Core\Plugin\ContextAwarePluginInterface $plugin
30 * The context-aware plugin.
31 * @param \Drupal\Component\Plugin\Context\ContextInterface[] $contexts
32 * An array of contexts.
35 * A form element for assigning context.
37 protected function addContextAssignmentElement(ContextAwarePluginInterface $plugin, array $contexts) {
39 foreach ($plugin->getContextDefinitions() as $context_slot => $definition) {
40 $valid_contexts = $this->contextHandler()->getMatchingContexts($contexts, $definition);
42 foreach ($valid_contexts as $context_id => $context) {
43 $element['#tree'] = TRUE;
44 $options[$context_id] = $context->getContextDefinition()->getLabel();
45 $element[$context_slot] = [
47 '#value' => $context_id,
51 if (count($options) > 1 || !$definition->isRequired()) {
52 $assignments = $plugin->getContextMapping();
53 $element[$context_slot] = [
54 '#title' => $definition->getLabel() ?: $this->t('Select a @context value:', ['@context' => $context_slot]),
56 '#options' => $options,
57 '#required' => $definition->isRequired(),
58 '#default_value' => !empty($assignments[$context_slot]) ? $assignments[$context_slot] : '',
59 '#description' => $definition->getDescription(),
61 if (!$definition->isRequired()) {
62 $element[$context_slot]['#empty_value'] = '';