ContextAwarePluginAssignmentTrait.php in Drupal 8
File
core/lib/Drupal/Core/Plugin/ContextAwarePluginAssignmentTrait.php
View source
<?php
namespace Drupal\Core\Plugin;
trait ContextAwarePluginAssignmentTrait {
protected abstract function t($string, array $args = [], array $options = []);
protected function contextHandler() {
return \Drupal::service('context.handler');
}
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,
];
}
if (count($options) > 1 || count($options) == 1 && !$definition
->isRequired()) {
$assignments = $plugin
->getContextMapping();
$element[$context_slot] = [
'#title' => $definition
->getLabel() ?: $this
->t('Select a @context value:', [
'@context' => $context_slot,
]),
'#type' => 'select',
'#options' => $options,
'#required' => $definition
->isRequired(),
'#default_value' => !empty($assignments[$context_slot]) ? $assignments[$context_slot] : '',
'#description' => $definition
->getDescription(),
];
if (!$definition
->isRequired()) {
$element[$context_slot]['#empty_value'] = '';
}
}
}
return $element;
}
}