ContextAwarePluginAssignmentTrait.php 2.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
<?php

namespace Drupal\Core\Plugin;

/**
 * Handles context assignments for context-aware plugins.
 */
trait ContextAwarePluginAssignmentTrait {

  /**
   * Ensures the t() method is available.
   *
   * @see \Drupal\Core\StringTranslation\StringTranslationTrait
   */
15
  abstract protected function t($string, array $args = [], array $options = []);
16 17 18 19 20 21 22 23 24 25 26 27 28

  /**
   * Wraps the context handler.
   *
   * @return \Drupal\Core\Plugin\Context\ContextHandlerInterface
   */
  protected function contextHandler() {
    return \Drupal::service('context.handler');
  }

  /**
   * Builds a form element for assigning a context to a given slot.
   *
29
   * @param \Drupal\Core\Plugin\ContextAwarePluginInterface $plugin
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
   *   The context-aware plugin.
   * @param \Drupal\Component\Plugin\Context\ContextInterface[] $contexts
   *   An array of contexts.
   *
   * @return array
   *   A form element for assigning context.
   */
  protected function addContextAssignmentElement(ContextAwarePluginInterface $plugin, array $contexts) {
    $element = [];
    foreach ($plugin->getContextDefinitions() as $context_slot => $definition) {
      $valid_contexts = $this->contextHandler()->getMatchingContexts($contexts, $definition);
      $options = [];
      foreach ($valid_contexts as $context_id => $context) {
        $element['#tree'] = TRUE;
        $options[$context_id] = $context->getContextDefinition()->getLabel();
        $element[$context_slot] = [
          '#type' => 'value',
          '#value' => $context_id,
        ];
      }

51 52 53 54
      // Show the context selector only if there is more than 1 option to choose
      // from. Also, show if there is a single option but the plugin does not
      // require a context.
      if (count($options) > 1 || (count($options) == 1 && !$definition->isRequired())) {
55 56
        $assignments = $plugin->getContextMapping();
        $element[$context_slot] = [
57
          '#title' => $definition->getLabel() ?: $this->t('Select a @context value:', ['@context' => $context_slot]),
58 59 60 61
          '#type' => 'select',
          '#options' => $options,
          '#required' => $definition->isRequired(),
          '#default_value' => !empty($assignments[$context_slot]) ? $assignments[$context_slot] : '',
62
          '#description' => $definition->getDescription(),
63
        ];
64 65 66
        if (!$definition->isRequired()) {
          $element[$context_slot]['#empty_value'] = '';
        }
67 68 69 70 71 72
      }
    }
    return $element;
  }

}