You are here

FieldBlock.php in Field as Block 8

Same filename in this branch
  1. 8 src/Plugin/Derivative/FieldBlock.php
  2. 8 src/Plugin/Block/FieldBlock.php
Same filename and directory in other branches
  1. 8.2 src/Plugin/Block/FieldBlock.php

File

src/Plugin/Block/FieldBlock.php
View source
<?php

/**
 * @file
 * Contains \Drupal\fieldblock\Plugin\Block\FieldBlock.
 */
namespace Drupal\fieldblock\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a fieldblock.
 *
 * @Block(
 *   id = "fieldblock",
 *   admin_label = @Translation("Fieldblock"),
 *   deriver = "Drupal\fieldblock\Plugin\Derivative\FieldBlock"
 * )
 */
class FieldBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $block_id = $this
      ->getDerivativeId();
    $block = $this::getFieldBlock($block_id);
    return $block;
  }

  /**
   * @var array[]
   *   Static storage for fields that are grabbed from the entity's render
   *   array, to be retrieved when fieldblocks are built.
   */
  protected static $fieldBlocks;

  /**
   * @param string $fieldblock_id
   *   The identifier of the fieldblock.
   * @return mixed[]|false
   *   The render array of the field that is published as block or false if the
   *   field is not available.
   */
  public static function getFieldBlock($fieldblock_id) {
    if (isset(self::$fieldBlocks[$fieldblock_id])) {
      return self::$fieldBlocks[$fieldblock_id];
    }
    else {
      return FALSE;
    }
  }

  /**
   * @param string $fieldblock_id
   *   The identifier of the fieldblock.
   * @param mixed[] $render_array
   *   The render array of the field that will be published as block.
   */
  public static function setFieldBlock($fieldblock_id, array $render_array) {
    self::$fieldBlocks[$fieldblock_id] = $render_array;
  }

  /**
   * #post_render_cache callback, temporarily stores a field's render array in a
   * static variable and returns the original element as post render cache
   * callbacks are supposed to do.
   *
   * Note that this is an atypical way to use the post render cache mechanism.
   * Post render cache is meant to allow modules to dynamically alter pieces of
   * cached content. Here we use it as some kind of context-aware cache, because
   * the cached field will only be retrieved and displayed as a block when the
   * entity is viewed.
   *
   * @param mixed[] $element
   *   The render array being rendered.
   * @param mixed[] $context
   *   Array containing the fieldblock ID and the field's render array.
   * @return mixed[]
   *   The render array being rendered.
   */
  public static function fieldBlockPostRenderCache(array $element, array $context) {
    self::setFieldBlock($context['fieldblock_id'], $context['build']);
    return $element;
  }

}

Classes

Namesort descending Description
FieldBlock Provides a fieldblock.