You are here

function fieldblock_entity_view_alter in Field as Block 8

Same name and namespace in other branches
  1. 7 fieldblock.module \fieldblock_entity_view_alter()

Implements hook_entity_view_alter().

Takes fields out of the current entity and caches them in a post render cache context. The #post_render_cache callback makes this data available to the fieldblock when it is built, We also hide the field from the render array.

Parameters

array &$build: A renderable array representing the entity content.

\Drupal\Core\Entity\EntityInterface $entity: The entity object being rendered. Not used in this implementation.

\Drupal\Core\Entity\Display\EntityViewDisplayInterface $display: The entity view display holding the display options configured for the entity components.

See also

\Drupal\fieldblock\Plugin\Block\FieldBlock::fieldBlockPostRenderCache

https://www.drupal.org/node/2151609

File

./fieldblock.module, line 96
Allow fields to be rendered in blocks.

Code

function fieldblock_entity_view_alter(array &$build, $entity, EntityViewDisplayInterface $display) {
  $fieldblock_settings = $display
    ->getThirdPartySettings('fieldblock');
  $display_id = $display
    ->get('id');
  foreach ($fieldblock_settings as $field_name => $field_label) {
    $fieldblock_id = $display_id . ':' . $field_name;
    if (count(\Drupal\Core\Render\Element::children($build[$field_name]))) {

      // This is where we take out the field and cache it in a post render
      // cache context.
      $build['#post_render_cache']['Drupal\\fieldblock\\Plugin\\Block\\FieldBlock::fieldBlockPostRenderCache'][] = array(
        'build' => $build[$field_name],
        'fieldblock_id' => $fieldblock_id,
      );
      hide($build[$field_name]);
    }
  }
}