View source
<?php
namespace Drupal\entity_reference_views_select\Plugin\Field\FieldWidget;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\Plugin\Field\FieldWidget\OptionsWidgetBase;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\RendererInterface;
use Drupal\views\ViewExecutableFactory;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
class EntityReferenceViewsOptionsButtonsWidget extends OptionsWidgetBase implements ContainerFactoryPluginInterface {
protected $renderer;
protected $viewFactory;
protected $viewLoader;
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')
->getStorage('view'), $container
->get('views.executable'), $container
->get('renderer'));
}
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, EntityStorageInterface $view_loader, ViewExecutableFactory $view_factory, RendererInterface $renderer) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);
$this->viewLoader = $view_loader;
$this->viewFactory = $view_factory;
$this->renderer = $renderer;
}
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
->getFieldSettings()['handler'] == 'views') {
$view = $this->viewFactory
->get($this->viewLoader
->load($this
->getFieldSettings()['handler_settings']['view']['view_name']));
$view
->setArguments($this
->getFieldSettings()['handler_settings']['view']['arguments']);
$view
->execute($this
->getFieldSettings()['handler_settings']['view']['display_name']);
$filter_options = [];
foreach ($view->result as $row) {
$row_output = $view->style_plugin->view->rowPlugin
->render($row);
$filter_options[$row->_entity
->id()] = $this->renderer
->render($row_output);
}
$options = $filter_options;
}
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,
];
}
return $element;
}
protected function getEmptyLabel() {
if (!$this->required && !$this->multiple) {
return $this
->t('N/A');
}
}
}