View source
<?php
namespace Drupal\workspace\Plugin\Field\FieldWidget;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\Plugin\Field\FieldWidget\OptionsWidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class OptionsTargetWorkspaceWidget extends OptionsWidgetBase implements ContainerFactoryPluginInterface {
protected $entityTypeManager;
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, EntityTypeManagerInterface $entity_type_manager) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);
$this->entityTypeManager = $entity_type_manager;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($plugin_id, $plugin_definition, $configuration['field_definition'], $configuration['settings'], $configuration['third_party_settings'], $container
->get('entity_type.manager'));
}
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element = parent::formElement($items, $delta, $element, $form, $form_state);
$options = $this
->getOptions($items
->getEntity());
$selected = $this
->getSelectedOptions($items);
if ($this->required && count($options) == 1) {
reset($options);
$selected = [
key($options),
];
}
if ($this->multiple) {
$element += [
'#type' => 'checkboxes',
'#default_value' => $selected,
'#options' => $options,
];
}
else {
$element += [
'#type' => 'radios',
'#default_value' => $selected ? reset($selected) : NULL,
'#options' => $options,
];
}
$not_available_workspaces = $this->entityTypeManager
->getStorage('workspace_pointer')
->loadByProperties([
'workspace_available' => FALSE,
]);
$not_available_keys = array_keys($not_available_workspaces);
foreach ($not_available_keys as $pointer_id) {
$element[$pointer_id]['#disabled'] = TRUE;
}
return $element;
}
}