WebformEntityTrait.php in Webform 6.x
File
src/Element/WebformEntityTrait.php
View source
<?php
namespace Drupal\webform\Element;
use Drupal\Core\Form\OptGroup;
use Drupal\webform\Utility\WebformOptionsHelper;
trait WebformEntityTrait {
public function getInfo() {
$info = parent::getInfo();
$info['#target_type'] = NULL;
$info['#selection_handler'] = 'default';
$info['#selection_settings'] = [];
return $info;
}
public static function setOptions(array &$element, array $settings = []) {
if (!empty($element['#options'])) {
return;
}
if (empty($element['#target_type'])) {
$element['#options'] = [];
return;
}
$selection_settings = isset($element['#selection_settings']) ? $element['#selection_settings'] : [];
$selection_handler_options = [
'target_type' => $element['#target_type'],
'handler' => $element['#selection_handler'],
'_webform_settings' => $settings,
] + $selection_settings;
$settings += [
'limit' => 0,
];
$selection_manager = \Drupal::service('plugin.manager.entity_reference_selection');
$handler = $selection_manager
->getInstance($selection_handler_options);
$referenceable_entities = $handler
->getReferenceableEntities(NULL, 'CONTAINS', $settings['limit']);
$options = [];
foreach ($referenceable_entities as $bundle_options) {
$options += $bundle_options;
}
if (!\Drupal::moduleHandler()
->moduleExists('views') || !$handler instanceof \Drupal\views\Plugin\EntityReferenceSelection\ViewsSelection) {
$options = static::translateOptions($options, $element);
}
if ($element['#type'] === 'webform_entity_select') {
$options = WebformOptionsHelper::stripTagsOptions($options);
}
else {
$options = OptGroup::flattenOptions($options);
}
$options = WebformOptionsHelper::decodeOptions($options);
$element['#options'] = $options;
}
protected static function translateOptions(array $options, array $element) {
$entity_repository = \Drupal::service('entity.repository');
foreach ($options as $key => $value) {
if (is_array($value)) {
$options[$key] = static::translateOptions($value, $element);
}
else {
$option = \Drupal::entityTypeManager()
->getStorage($element['#target_type'])
->load($key);
$option = $entity_repository
->getTranslationFromContext($option);
$options[$key] = $option
->label();
}
}
return $options;
}
}