You are here

class Block in Views (for Drupal 7) 8.3

The plugin that handles a block.

Plugin annotation


@Plugin(
  id = "block",
  module = "block",
  title = @Translation("Block"),
  help = @Translation("Display the view as a block."),
  theme = "views_view",
  uses_hook_block = TRUE,
  contextual_links_locations = {"block"},
  admin = @Translation("Block")
)

Hierarchy

Expanded class hierarchy of Block

Related topics

4 string references to 'Block'
views.view.archive.yml in config/views.view.archive.yml
config/views.view.archive.yml
views.view.comments_recent.yml in config/views.view.comments_recent.yml
config/views.view.comments_recent.yml
views.view.test_display.yml in tests/views_test_config/config/views.view.test_display.yml
tests/views_test_config/config/views.view.test_display.yml
WizardPluginBase::addDisplays in lib/Drupal/views/Plugin/views/wizard/WizardPluginBase.php
Adds the array of display options to the view, with appropriate overrides.

File

lib/Views/block/Plugin/views/display/Block.php, line 31
Definition of Drupal\views\Plugin\views\display\Block. Definition of Views\block\Plugin\views\display\Block.

Namespace

Views\block\Plugin\views\display
View source
class Block extends DisplayPluginBase {

  /**
   * Whether the display allows attachments.
   *
   * @var bool
   */
  protected $usesAttachments = TRUE;
  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['block_description'] = array(
      'default' => '',
      'translatable' => TRUE,
    );
    $options['block_caching'] = array(
      'default' => DRUPAL_NO_CACHE,
    );
    return $options;
  }

  /**
   * The default block handler doesn't support configurable items,
   * but extended block handlers might be able to do interesting
   * stuff with it.
   */
  public function executeHookBlockList($delta = 0, $edit = array()) {
    $delta = $this->view->storage->name . '-' . $this->display['id'];
    $desc = $this
      ->getOption('block_description');
    if (empty($desc)) {
      if ($this->display['display_title'] == $this->definition['title']) {
        $desc = t('View: !view', array(
          '!view' => $this->view->storage
            ->getHumanName(),
        ));
      }
      else {
        $desc = t('View: !view: !display', array(
          '!view' => $this->view->storage
            ->getHumanName(),
          '!display' => $this->display['display_title'],
        ));
      }
    }
    return array(
      $delta => array(
        'info' => $desc,
        'cache' => $this
          ->getCacheType(),
      ),
    );
  }

  /**
   * The display block handler returns the structure necessary for a block.
   */
  public function execute() {

    // Prior to this being called, the $view should already be set to this
    // display, and arguments should be set on the view.
    $info['content'] = $this->view
      ->render();
    $info['subject'] = filter_xss_admin($this->view
      ->getTitle());
    if (!empty($this->view->result) || $this
      ->getOption('empty') || !empty($this->view->style_plugin->definition['even empty'])) {
      return $info;
    }
  }

  /**
   * Provide the summary for page options in the views UI.
   *
   * This output is returned as an array.
   */
  public function optionsSummary(&$categories, &$options) {

    // It is very important to call the parent function here:
    parent::optionsSummary($categories, $options);
    $categories['block'] = array(
      'title' => t('Block settings'),
      'column' => 'second',
      'build' => array(
        '#weight' => -10,
      ),
    );
    $block_description = strip_tags($this
      ->getOption('block_description'));
    if (empty($block_description)) {
      $block_description = t('None');
    }
    $options['block_description'] = array(
      'category' => 'block',
      'title' => t('Block name'),
      'value' => views_ui_truncate($block_description, 24),
    );
    $types = $this
      ->blockCachingModes();
    $options['block_caching'] = array(
      'category' => 'other',
      'title' => t('Block caching'),
      'value' => $types[$this
        ->getCacheType()],
    );
  }

  /**
   * Provide a list of core's block caching modes.
   */
  protected function blockCachingModes() {
    return array(
      DRUPAL_NO_CACHE => t('Do not cache'),
      DRUPAL_CACHE_GLOBAL => t('Cache once for everything (global)'),
      DRUPAL_CACHE_PER_PAGE => t('Per page'),
      DRUPAL_CACHE_PER_ROLE => t('Per role'),
      DRUPAL_CACHE_PER_ROLE | DRUPAL_CACHE_PER_PAGE => t('Per role per page'),
      DRUPAL_CACHE_PER_USER => t('Per user'),
      DRUPAL_CACHE_PER_USER | DRUPAL_CACHE_PER_PAGE => t('Per user per page'),
    );
  }

  /**
   * Provide a single method to figure caching type, keeping a sensible default
   * for when it's unset.
   */
  protected function getCacheType() {
    $cache_type = $this
      ->getOption('block_caching');
    if (empty($cache_type)) {
      $cache_type = DRUPAL_NO_CACHE;
    }
    return $cache_type;
  }

  /**
   * Provide the default form for setting options.
   */
  public function buildOptionsForm(&$form, &$form_state) {

    // It is very important to call the parent function here:
    parent::buildOptionsForm($form, $form_state);
    switch ($form_state['section']) {
      case 'block_description':
        $form['#title'] .= t('Block admin description');
        $form['block_description'] = array(
          '#type' => 'textfield',
          '#description' => t('This will appear as the name of this block in administer >> structure >> blocks.'),
          '#default_value' => $this
            ->getOption('block_description'),
        );
        break;
      case 'block_caching':
        $form['#title'] .= t('Block caching type');
        $form['block_caching'] = array(
          '#type' => 'radios',
          '#description' => t("This sets the default status for Drupal's built-in block caching method; this requires that caching be turned on in block administration, and be careful because you have little control over when this cache is flushed."),
          '#options' => $this
            ->blockCachingModes(),
          '#default_value' => $this
            ->getCacheType(),
        );
        break;
      case 'exposed_form_options':
        $this->view
          ->initHandlers();
        if (!$this
          ->usesExposed() && parent::usesExposed()) {
          $form['exposed_form_options']['warning'] = array(
            '#weight' => -10,
            '#markup' => '<div class="messages warning">' . t('Exposed filters in block displays require "Use AJAX" to be set to work correctly.') . '</div>',
          );
        }
    }
  }

  /**
   * Perform any necessary changes to the form values prior to storage.
   * There is no need for this function to actually store the data.
   */
  public function submitOptionsForm(&$form, &$form_state) {

    // It is very important to call the parent function here:
    parent::submitOptionsForm($form, $form_state);
    switch ($form_state['section']) {
      case 'display_id':
        $this
          ->updateBlockBid($form_state['view']->storage->name, $this->display['id'], $this->display['new_id']);
        break;
      case 'block_description':
        $this
          ->setOption('block_description', $form_state['values']['block_description']);
        break;
      case 'block_caching':
        $this
          ->setOption('block_caching', $form_state['values']['block_caching']);
        $this
          ->saveBlockCache($form_state['view']->storage->name . '-' . $form_state['display_id'], $form_state['values']['block_caching']);
        break;
    }
  }

  /**
   * Block views use exposed widgets only if AJAX is set.
   */
  public function usesExposed() {
    if ($this
      ->isAJAXEnabled()) {
      return parent::usesExposed();
    }
    return FALSE;
  }

  /**
   * Update the block delta when you change the machine readable name of the display.
   */
  protected function updateBlockBid($name, $old_delta, $delta) {
    $old_hashes = $hashes = variable_get('views_block_hashes', array());
    $old_delta = $name . '-' . $old_delta;
    $delta = $name . '-' . $delta;
    if (strlen($old_delta) >= 32) {
      $old_delta = md5($old_delta);
      unset($hashes[$old_delta]);
    }
    if (strlen($delta) >= 32) {
      $md5_delta = md5($delta);
      $hashes[$md5_delta] = $delta;
      $delta = $md5_delta;
    }

    // Maybe people don't have block module installed, so let's skip this.
    if (db_table_exists('block')) {
      db_update('block')
        ->fields(array(
        'delta' => $delta,
      ))
        ->condition('delta', $old_delta)
        ->execute();
    }

    // Update the hashes if needed.
    if ($hashes != $old_hashes) {
      variable_set('views_block_hashes', $hashes);
    }
  }

  /**
   * Save the block cache setting in the blocks table if this block allready
   * exists in the blocks table. Dirty fix untill http://drupal.org/node/235673 gets in.
   */
  protected function saveBlockCache($delta, $cache_setting) {
    if (strlen($delta) >= 32) {
      $delta = md5($delta);
    }
    if (db_table_exists('block') && ($bid = db_query("SELECT bid FROM {block} WHERE module = 'views' AND delta = :delta", array(
      ':delta' => $delta,
    ))
      ->fetchField())) {
      db_update('block')
        ->fields(array(
        'cache' => $cache_setting,
      ))
        ->condition('module', 'views')
        ->condition('delta', $delta)
        ->execute();
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
Block::$usesAttachments protected property Whether the display allows attachments. Overrides DisplayPluginBase::$usesAttachments
Block::blockCachingModes protected function Provide a list of core's block caching modes.
Block::buildOptionsForm public function Provide the default form for setting options. Overrides DisplayPluginBase::buildOptionsForm
Block::defineOptions protected function Information about options for all kinds of purposes will be held here. @code 'option_name' => array( Overrides DisplayPluginBase::defineOptions
Block::execute public function The display block handler returns the structure necessary for a block. Overrides DisplayPluginBase::execute
Block::executeHookBlockList public function The default block handler doesn't support configurable items, but extended block handlers might be able to do interesting stuff with it.
Block::getCacheType protected function Provide a single method to figure caching type, keeping a sensible default for when it's unset.
Block::optionsSummary public function Provide the summary for page options in the views UI. Overrides DisplayPluginBase::optionsSummary
Block::saveBlockCache protected function Save the block cache setting in the blocks table if this block allready exists in the blocks table. Dirty fix untill http://drupal.org/node/235673 gets in.
Block::submitOptionsForm public function Perform any necessary changes to the form values prior to storage. There is no need for this function to actually store the data. Overrides DisplayPluginBase::submitOptionsForm
Block::updateBlockBid protected function Update the block delta when you change the machine readable name of the display.
Block::usesExposed public function Block views use exposed widgets only if AJAX is set. Overrides DisplayPluginBase::usesExposed
DisplayPluginBase::$extender property Stores all available display extenders.
DisplayPluginBase::$handlers property
DisplayPluginBase::$output public property Stores the rendered output of the display.
DisplayPluginBase::$plugins protected property An array of instantiated plugins used in this display.
DisplayPluginBase::$usesAJAX protected property Whether the display allows the use of AJAX or not. 1
DisplayPluginBase::$usesMore protected property Whether the display allows the use of a 'more' link or not.
DisplayPluginBase::$usesOptions protected property Overrides Drupal\views\Plugin\Plugin::$usesOptions. Overrides PluginBase::$usesOptions
DisplayPluginBase::$usesPager protected property Whether the display allows the use of a pager or not. 2
DisplayPluginBase::$view property The top object of a view. Overrides PluginBase::$view
DisplayPluginBase::acceptAttachments public function Determines whether this display can use attachments.
DisplayPluginBase::access public function Determine if the user has access to this display of the view.
DisplayPluginBase::attachTo public function Allow displays to attach to other views. 2
DisplayPluginBase::defaultableSections public function Static member function to list which sections are defaultable and what items each section contains. 1
DisplayPluginBase::destroy public function Clears a plugin. Overrides PluginBase::destroy
DisplayPluginBase::displaysExposed public function Determine if this display should display the exposed filters widgets, so the view will know whether or not to render them. 1
DisplayPluginBase::formatThemes protected function Format a list of theme templates for output by the theme info helper.
DisplayPluginBase::getArgumentsTokens public function Returns to tokens for arguments.
DisplayPluginBase::getArgumentText public function Provide some helpful text for the arguments. The result should contain of an array with 1
DisplayPluginBase::getFieldLabels public function Retrieve a list of fields for the current display with the relationship associated if it exists.
DisplayPluginBase::getHandler public function Get the handler object for a single handler.
DisplayPluginBase::getHandlers public function Get a full array of handlers for $type. This caches them.
DisplayPluginBase::getLinkDisplay public function Check to see which display to use when creating links within a view using this display.
DisplayPluginBase::getOption public function Intelligently get an option either from this display or from the default display, if directed to do so.
DisplayPluginBase::getPagerText public function Provide some helpful text for pagers. 1
DisplayPluginBase::getPath public function Return the base path to use for this display.
DisplayPluginBase::getPlugin public function Get the instance of a plugin, for example style or row.
DisplayPluginBase::getSpecialBlocks public function Provide the block system with any exposed widget blocks for this display.
DisplayPluginBase::getStyleType protected function Displays can require a certain type of style plugin. By default, they will be 'normal'. 1
DisplayPluginBase::getUrl public function
DisplayPluginBase::hasPath public function Check to see if the display has a 'path' field. 1
DisplayPluginBase::hookBlockList public function If this display creates a block, implement one of these.
DisplayPluginBase::hookMenu public function If this display creates a page with a menu item, implement it here.
DisplayPluginBase::init public function 1
DisplayPluginBase::isAJAXEnabled public function Whether the display is actually using AJAX or not.
DisplayPluginBase::isDefaultDisplay public function Determine if this display is the 'default' display which contains fallback settings 1
DisplayPluginBase::isDefaulted public function Determine if a given option is set to use the default display or the current display
DisplayPluginBase::isEnabled public function Whether the display is enabled.
DisplayPluginBase::isIdentifierUnique public function Check if the provided identifier is unique.
DisplayPluginBase::isMoreEnabled public function Whether the display is using the 'more' link or not.
DisplayPluginBase::isPagerEnabled public function Whether the display is using a pager or not.
DisplayPluginBase::optionLink public function Because forms may be split up into sections, this provides an easy URL to exactly the right section. Don't override this.
DisplayPluginBase::optionsOverride public function If override/revert was clicked, perform the proper toggle.
DisplayPluginBase::overrideOption public function Set an option and force it to be an override.
DisplayPluginBase::preExecute public function Set up any variables on the view prior to execution. These are separated from execute because they are extremely common and unlikely to be overridden on an individual display.
DisplayPluginBase::preview function Fully render the display for the purposes of a live preview or some other AJAXy reason. 2
DisplayPluginBase::query public function Inject anything into the query that the display handler needs. Overrides PluginBase::query
DisplayPluginBase::render public function Render this display. 1
DisplayPluginBase::renderArea public function
DisplayPluginBase::renderEmpty public function
DisplayPluginBase::renderFilters public function Not all display plugins will support filtering
DisplayPluginBase::renderFooter public function Render the footer of the view.
DisplayPluginBase::renderHeader public function Render the header of the view.
DisplayPluginBase::renderMoreLink public function Render the 'more' link
DisplayPluginBase::renderPager public function Not all display plugins will suppert pager rendering. 1
DisplayPluginBase::setOption public function Intelligently set an option either from this display or from the default display, if directed to do so.
DisplayPluginBase::setOverride public function Flip the override setting for the given section.
DisplayPluginBase::useGroupBy public function Does the display have groupby enabled?
DisplayPluginBase::useMoreAlways public function Should the enabled display more link be shown when no more items?
DisplayPluginBase::useMoreText public function Does the display have custom link text?
DisplayPluginBase::usesAJAX public function Whether the display allows the use of AJAX or not. 1
DisplayPluginBase::usesAttachments public function Returns whether the display can use attachments. 4
DisplayPluginBase::usesBreadcrumb public function Check to see if the display needs a breadcrumb 1
DisplayPluginBase::usesExposedFormInBlock public function Check to see if the display can put the exposed formin a block.
DisplayPluginBase::usesFields public function Determine if the display's style uses fields.
DisplayPluginBase::usesLinkDisplay public function Check to see if the display has some need to link to another display. 1
DisplayPluginBase::usesMore public function Whether the display allows the use of a 'more' link or not.
DisplayPluginBase::usesPager public function Whether the display allows the use of a pager or not. 2
DisplayPluginBase::validate public function Make sure the display and all associated handlers are valid. Overrides PluginBase::validate 1
DisplayPluginBase::validateOptionsForm public function Validate the options form. Overrides PluginBase::validateOptionsForm 2
DisplayPluginBase::viewSpecialBlocks public function Render any special blocks provided for this display.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$definition public property Plugins's definition
PluginBase::$displayHandler public property The display object this plugin is for.
PluginBase::$options public property Options for this plugin will be held here.
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::additionalThemeFunctions public function Provide a list of additional theme functions for the theme information page
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginBase::pluginTitle public function Return the human readable name of the display.
PluginBase::setOptionDefaults protected function
PluginBase::summaryTitle public function Returns the summary of the settings in the display. 6
PluginBase::themeFunctions public function Provide a full list of possible theme templates used by this style. 1
PluginBase::unpackOptions public function Unpack options over our existing defaults, drilling down into arrays so that defaults don't get totally blown away.
PluginBase::usesOptions public function Returns the usesOptions property. 8
PluginBase::__construct public function Constructs a Plugin object. Overrides PluginBase::__construct 2