ViewsBlockBase.php 6.93 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\views\Plugin\Block;

5
use Drupal\Core\Access\AccessResult;
6
use Drupal\Core\Block\BlockBase;
7
use Drupal\Core\Form\FormStateInterface;
8 9
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\views\ViewExecutableFactory;
10
use Drupal\Core\Entity\EntityStorageInterface;
11
use Symfony\Component\DependencyInjection\ContainerInterface;
12
use Drupal\Core\Session\AccountInterface;
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

/**
 * Base class for Views block plugins.
 */
abstract class ViewsBlockBase extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * The View executable object.
   *
   * @var \Drupal\views\ViewExecutable
   */
  protected $view;

  /**
   * The display ID being used for this View.
   *
   * @var string
   */
  protected $displayID;

  /**
   * Indicates whether the display was successfully set.
   *
   * @var bool
   */
  protected $displaySet;

  /**
41 42 43 44 45 46 47 48
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $user;

  /**
   * Constructs a \Drupal\views\Plugin\Block\ViewsBlockBase object.
49 50 51 52 53
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
54
   * @param mixed $plugin_definition
55 56 57
   *   The plugin implementation definition.
   * @param \Drupal\views\ViewExecutableFactory $executable_factory
   *   The view executable factory.
58 59
   * @param \Drupal\Core\Entity\EntityStorageInterface $storage
   *   The views storage.
60 61
   * @param \Drupal\Core\Session\AccountInterface $user
   *   The current user.
62
   */
63
  public function __construct(array $configuration, $plugin_id, $plugin_definition, ViewExecutableFactory $executable_factory, EntityStorageInterface $storage, AccountInterface $user) {
64
    $this->pluginId = $plugin_id;
65
    $delta = $this->getDerivativeId();
66 67
    list($name, $this->displayID) = explode('-', $delta, 2);
    // Load the view.
68
    $view = $storage->load($name);
69 70
    $this->view = $executable_factory->get($view);
    $this->displaySet = $this->view->setDisplay($this->displayID);
71
    $this->user = $user;
72 73 74 75 76 77 78

    parent::__construct($configuration, $plugin_id, $plugin_definition);
  }

  /**
   * {@inheritdoc}
   */
79
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
80 81 82
    return new static(
      $configuration, $plugin_id, $plugin_definition,
      $container->get('views.executable'),
83
      $container->get('entity.manager')->getStorage('view'),
84
      $container->get('current_user')
85 86 87 88 89 90
    );
  }

  /**
   * {@inheritdoc}
   */
91
  protected function blockAccess(AccountInterface $account) {
92 93 94 95 96 97 98
    if ($this->view->access($this->displayID)) {
      $access = AccessResult::allowed();
    }
    else {
      $access = AccessResult::forbidden();
    }
    return $access;
99 100
  }

101 102 103 104
  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
105
    return ['views_label' => ''];
106 107
  }

108 109 110 111 112 113 114
  /**
   * {@inheritdoc}
   */
  public function getPlaceholderString() {
    return $this->t('Placeholder for the "@view" views block', ['@view' => $this->view->storage->label()]);
  }

115 116 117
  /**
   * {@inheritdoc}
   */
118
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
119 120 121 122 123 124
    $form = parent::buildConfigurationForm($form, $form_state);

    // Set the default label to '' so the views internal title is used.
    $form['label']['#default_value'] = '';
    $form['label']['#access'] = FALSE;

125
    // Unset the machine_name provided by BlockForm.
126 127 128 129 130 131
    unset($form['id']['#machine_name']['source']);
    // Prevent users from changing the auto-generated block machine_name.
    $form['id']['#access'] = FALSE;
    $form['#pre_render'][] = '\Drupal\views\Plugin\views\PluginBase::preRenderAddFieldsetMarkup';

    // Allow to override the label on the actual page.
132
    $form['views_label_checkbox'] = [
133 134 135
      '#type' => 'checkbox',
      '#title' => $this->t('Override title'),
      '#default_value' => !empty($this->configuration['views_label']),
136
    ];
137

138
    $form['views_label_fieldset'] = [
139
      '#type' => 'fieldset',
140 141 142 143 144 145 146 147 148 149
      '#states' => [
        'visible' => [
          [
            ':input[name="settings[views_label_checkbox]"]' => ['checked' => TRUE],
          ],
        ],
      ],
    ];

    $form['views_label'] = [
150 151 152
      '#title' => $this->t('Title'),
      '#type' => 'textfield',
      '#default_value' => $this->configuration['views_label'] ?: $this->view->getTitle(),
153 154 155 156 157 158 159
      '#states' => [
        'visible' => [
          [
            ':input[name="settings[views_label_checkbox]"]' => ['checked' => TRUE],
          ],
        ],
      ],
160
      '#fieldset' => 'views_label_fieldset',
161
    ];
162 163

    if ($this->view->storage->access('edit') && \Drupal::moduleHandler()->moduleExists('views_ui')) {
164
      $form['views_label']['#description'] = $this->t('Changing the title here means it cannot be dynamically altered anymore. (Try changing it directly in <a href=":url">@name</a>.)', [':url' => \Drupal::url('entity.view.edit_display_form', ['view' => $this->view->storage->id(), 'display_id' => $this->displayID]), '@name' => $this->view->storage->label()]);
165 166 167 168 169
    }
    else {
      $form['views_label']['#description'] = $this->t('Changing the title here means it cannot be dynamically altered anymore.');
    }

170 171 172
    return $form;
  }

173 174 175
  /**
   * {@inheritdoc}
   */
176
  public function blockSubmit($form, FormStateInterface $form_state) {
177 178
    if (!$form_state->isValueEmpty('views_label_checkbox')) {
      $this->configuration['views_label'] = $form_state->getValue('views_label');
179 180 181 182
    }
    else {
      $this->configuration['views_label'] = '';
    }
183
    $form_state->unsetValue('views_label_checkbox');
184 185
  }

186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
  /**
   * Converts Views block content to a renderable array with contextual links.
   *
   * @param string|array $output
   *   An string|array representing the block. This will be modified to be a
   *   renderable array, containing the optional '#contextual_links' property (if
   *   there are any contextual links associated with the block).
   * @param string $block_type
   *   The type of the block. If it's 'block' it's a regular views display,
   *   but 'exposed_filter' exist as well.
   */
  protected function addContextualLinks(&$output, $block_type = 'block') {
    // Do not add contextual links to an empty block.
    if (!empty($output)) {
      // Contextual links only work on blocks whose content is a renderable
      // array, so if the block contains a string of already-rendered markup,
      // convert it to an array.
      if (is_string($output)) {
204
        $output = ['#markup' => $output];
205
      }
206 207 208 209 210 211 212

      // views_add_contextual_links() needs the following information in
      // order to be attached to the view.
      $output['#view_id'] = $this->view->storage->id();
      $output['#view_display_show_admin_links'] = $this->view->getShowAdminLinks();
      $output['#view_display_plugin_id'] = $this->view->display_handler->getPluginId();
      views_add_contextual_links($output, $block_type, $this->displayID);
213 214 215 216
    }
  }

}