-
Marc van Gend authoredMarc van Gend authored
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
FieldBlock.php 2.15 KiB
<?php
/**
* @file
* Contains \Drupal\fieldblock\Plugin\Block\FieldBlock.
*/
namespace Drupal\fieldblock\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Cache\CacheBackendInterface;
/**
* Provides a fieldblock.
*
* @Block(
* id = "fieldblock",
* admin_label = @Translation("Fieldblock"),
* deriver = "Drupal\fieldblock\Plugin\Derivative\FieldBlock"
* )
*/
class FieldBlock extends BlockBase {
/**
* Implements \Drupal\block\BlockBase::blockBuild().
*/
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 $block_id
* The identifier of the fieldblock.
* @return array | false
* The render array of the field that is published as block or false if the
* field is not available.
*/
public static function getFieldBlock($block_id) {
if (isset(self::$fieldBlocks[$block_id])) {
return self::$fieldBlocks[$block_id];
}
else {
return FALSE;
}
}
/**
* #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 array $element
* The element (entity) being rendered.
* @param array $context
* Array containing the fieldblock ID and the field's render array.
* @return array
* The render array of the entity.
*/
public static function fieldBlockPostRenderCache(array $element, array $context) {
self::$fieldBlocks[$context['fieldblock_id']] = $context['build'];
return $element;
}
}