WebformEntityReferenceSelectWidget.php in Webform 8.5
File
src/Plugin/Field/FieldWidget/WebformEntityReferenceSelectWidget.php
View source
<?php
namespace Drupal\webform\Plugin\Field\FieldWidget;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Entity\Webform;
use Drupal\webform\WebformInterface;
use Drupal\Core\Field\Plugin\Field\FieldWidget\OptionsWidgetBase;
class WebformEntityReferenceSelectWidget extends OptionsWidgetBase {
use WebformEntityReferenceWidgetTrait;
public static function defaultSettings() {
return [
'default_data' => TRUE,
'webforms' => [],
] + parent::defaultSettings();
}
public function getTargetIdElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$referenced_entities = $items
->referencedEntities();
$default_value = isset($referenced_entities[$delta]) ? $referenced_entities[$delta] : NULL;
if ($default_value instanceof WebformInterface) {
$default_value = $default_value
->id();
}
$options = $this
->getOptions($items
->getEntity());
if ($default_value && ($webform = Webform::load($default_value))) {
if ($webform
->isArchived()) {
$options[(string) $this
->t('Archived')][$webform
->id()] = $webform
->label();
}
}
$target_element = [
'#type' => 'webform_entity_select',
'#options' => $options,
'#default_value' => $default_value,
];
if (empty($element['#required'])) {
$target_element['#empty_option'] = $this
->t('- Select -');
$target_element['#empty_value'] = '';
}
$target_element['#element_validate'] = [
[
get_class($this),
'validateWebformEntityReferenceSelectWidget',
],
];
return $target_element;
}
public static function validateWebformEntityReferenceSelectWidget(&$element, FormStateInterface $form_state, &$complete_form) {
$value = !empty($element['#value']) ? $element['#value'] : NULL;
$form_state
->setValueForElement($element, $value);
}
protected function getOptions(FieldableEntityInterface $entity) {
if (!isset($this->options)) {
$webform_ids = $this
->getSetting('webforms');
if ($webform_ids) {
$webforms = Webform::loadMultiple($webform_ids);
$options = [];
foreach ($webforms as $webform) {
$options[$webform
->id()] = $webform
->label();
}
asort($options);
}
else {
$options = $this->fieldDefinition
->getFieldStorageDefinition()
->getOptionsProvider($this->column, $entity)
->getSettableOptions(\Drupal::currentUser());
}
$module_handler = \Drupal::moduleHandler();
$context = [
'fieldDefinition' => $this->fieldDefinition,
'entity' => $entity,
];
$module_handler
->alter('options_list', $options, $context);
array_walk_recursive($options, [
$this,
'sanitizeLabel',
]);
$this->options = $options;
}
return $this->options;
}
}