View source
<?php
namespace Drupal\system\Plugin\views\field;
use Drupal\Core\Cache\CacheableDependencyInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Entity\RevisionableInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Routing\RedirectDestinationTrait;
use Drupal\Core\TypedData\TranslatableInterface;
use Drupal\views\Entity\Render\EntityTranslationRenderTrait;
use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\Plugin\views\field\UncacheableFieldHandlerTrait;
use Drupal\views\Plugin\views\style\Table;
use Drupal\views\ResultRow;
use Drupal\views\ViewExecutable;
use Symfony\Component\DependencyInjection\ContainerInterface;
class BulkForm extends FieldPluginBase implements CacheableDependencyInterface {
use RedirectDestinationTrait;
use UncacheableFieldHandlerTrait;
use EntityTranslationRenderTrait;
protected $entityManager;
protected $actionStorage;
protected $actions = array();
protected $languageManager;
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityManagerInterface $entity_manager, LanguageManagerInterface $language_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityManager = $entity_manager;
$this->actionStorage = $entity_manager
->getStorage('action');
$this->languageManager = $language_manager;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('entity.manager'), $container
->get('language_manager'));
}
public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
parent::init($view, $display, $options);
$entity_type = $this
->getEntityType();
$this->actions = array_filter($this->actionStorage
->loadMultiple(), function ($action) use ($entity_type) {
return $action
->getType() == $entity_type;
});
}
public function getCacheMaxAge() {
return 0;
}
public function getCacheContexts() {
return $this->languageManager
->isMultilingual() ? $this
->getEntityTranslationRenderer()
->getCacheContexts() : [];
}
public function getCacheTags() {
return [];
}
public function getEntityTypeId() {
return $this
->getEntityType();
}
protected function getEntityManager() {
return $this->entityManager;
}
protected function getLanguageManager() {
return $this->languageManager;
}
protected function getView() {
return $this->view;
}
protected function defineOptions() {
$options = parent::defineOptions();
$options['action_title'] = array(
'default' => $this
->t('With selection'),
);
$options['include_exclude'] = array(
'default' => 'exclude',
);
$options['selected_actions'] = array(
'default' => array(),
);
return $options;
}
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
$form['action_title'] = array(
'#type' => 'textfield',
'#title' => $this
->t('Action title'),
'#default_value' => $this->options['action_title'],
'#description' => $this
->t('The title shown above the actions dropdown.'),
);
$form['include_exclude'] = array(
'#type' => 'radios',
'#title' => $this
->t('Available actions'),
'#options' => array(
'exclude' => $this
->t('All actions, except selected'),
'include' => $this
->t('Only selected actions'),
),
'#default_value' => $this->options['include_exclude'],
);
$form['selected_actions'] = array(
'#type' => 'checkboxes',
'#title' => $this
->t('Selected actions'),
'#options' => $this
->getBulkOptions(FALSE),
'#default_value' => $this->options['selected_actions'],
);
parent::buildOptionsForm($form, $form_state);
}
public function validateOptionsForm(&$form, FormStateInterface $form_state) {
parent::validateOptionsForm($form, $form_state);
$selected_actions = $form_state
->getValue(array(
'options',
'selected_actions',
));
$form_state
->setValue(array(
'options',
'selected_actions',
), array_values(array_filter($selected_actions)));
}
public function preRender(&$values) {
parent::preRender($values);
if (!empty($this->view->style_plugin) && $this->view->style_plugin instanceof Table) {
$this->options['element_label_class'] .= 'select-all';
$this->options['label'] = '';
}
}
public function getValue(ResultRow $row, $field = NULL) {
return '<!--form-item-' . $this->options['id'] . '--' . $row->index . '-->';
}
public function viewsForm(&$form, FormStateInterface $form_state) {
$form['#cache']['max-age'] = 0;
$form['#attached']['library'][] = 'core/drupal.tableselect';
$use_revision = array_key_exists('revision', $this->view
->getQuery()
->getEntityTableInfo());
if (!empty($this->view->result)) {
$form[$this->options['id']]['#tree'] = TRUE;
foreach ($this->view->result as $row_index => $row) {
$entity = $this
->getEntityTranslation($this
->getEntity($row), $row);
$form[$this->options['id']][$row_index] = array(
'#type' => 'checkbox',
'#title' => $this
->t('Update this item'),
'#title_display' => 'invisible',
'#default_value' => !empty($form_state
->getValue($this->options['id'])[$row_index]) ? 1 : NULL,
'#return_value' => $this
->calculateEntityBulkFormKey($entity, $use_revision),
);
}
$form['actions']['submit']['#value'] = $this
->t('Apply');
$form['header'] = array(
'#type' => 'container',
'#weight' => -100,
);
$form['header'][$this->options['id']] = array(
'#type' => 'container',
);
$form['header'][$this->options['id']]['action'] = array(
'#type' => 'select',
'#title' => $this->options['action_title'],
'#options' => $this
->getBulkOptions(),
);
$form['header'][$this->options['id']]['actions'] = $form['actions'];
}
else {
unset($form['actions']);
}
}
protected function getBulkOptions($filtered = TRUE) {
$options = array();
foreach ($this->actions as $id => $action) {
if ($filtered) {
$in_selected = in_array($id, $this->options['selected_actions']);
if ($this->options['include_exclude'] == 'include' && !$in_selected) {
continue;
}
elseif ($this->options['include_exclude'] == 'exclude' && $in_selected) {
continue;
}
}
$options[$id] = $action
->label();
}
return $options;
}
public function viewsFormSubmit(&$form, FormStateInterface $form_state) {
if ($form_state
->get('step') == 'views_form_views_form') {
$selected = array_filter($form_state
->getValue($this->options['id']));
$entities = array();
$action = $this->actions[$form_state
->getValue('action')];
$count = 0;
foreach ($selected as $bulk_form_key) {
$entity = $this
->loadEntityFromBulkFormKey($bulk_form_key);
if (!$action
->getPlugin()
->access($entity, $this->view
->getUser())) {
$this
->drupalSetMessage($this
->t('No access to execute %action on the @entity_type_label %entity_label.', [
'%action' => $action
->label(),
'@entity_type_label' => $entity
->getEntityType()
->getLabel(),
'%entity_label' => $entity
->label(),
]), 'error');
continue;
}
$count++;
$entities[$bulk_form_key] = $entity;
}
$action
->execute($entities);
$operation_definition = $action
->getPluginDefinition();
if (!empty($operation_definition['confirm_form_route_name'])) {
$options = array(
'query' => $this
->getDestinationArray(),
);
$form_state
->setRedirect($operation_definition['confirm_form_route_name'], array(), $options);
}
else {
$count = count(array_filter($form_state
->getValue($this->options['id'])));
if ($count) {
drupal_set_message($this
->formatPlural($count, '%action was applied to @count item.', '%action was applied to @count items.', array(
'%action' => $action
->label(),
)));
}
}
}
}
protected function emptySelectedMessage() {
return $this
->t('No items selected.');
}
public function viewsFormValidate(&$form, FormStateInterface $form_state) {
$selected = array_filter($form_state
->getValue($this->options['id']));
if (empty($selected)) {
$form_state
->setErrorByName('', $this
->emptySelectedMessage());
}
}
public function query() {
if ($this->languageManager
->isMultilingual()) {
$this
->getEntityTranslationRenderer()
->query($this->query, $this->relationship);
}
}
public function clickSortable() {
return FALSE;
}
protected function drupalSetMessage($message = NULL, $type = 'status', $repeat = FALSE) {
drupal_set_message($message, $type, $repeat);
}
protected function calculateEntityBulkFormKey(EntityInterface $entity, $use_revision) {
$key_parts = [
$entity
->language()
->getId(),
$entity
->id(),
];
if ($entity instanceof RevisionableInterface && $use_revision) {
$key_parts[] = $entity
->getRevisionId();
}
$key = json_encode($key_parts);
return base64_encode($key);
}
protected function loadEntityFromBulkFormKey($bulk_form_key) {
$key = base64_decode($bulk_form_key);
$key_parts = json_decode($key);
$revision_id = NULL;
if (count($key_parts) === 3) {
$revision_id = array_pop($key_parts);
}
$id = array_pop($key_parts);
$langcode = array_pop($key_parts);
$storage = $this->entityManager
->getStorage($this
->getEntityType());
$entity = $revision_id ? $storage
->loadRevision($revision_id) : $storage
->load($id);
if ($entity instanceof TranslatableInterface) {
$entity = $entity
->getTranslation($langcode);
}
return $entity;
}
}