You are here

public function FieldBlock::build in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/layout_builder/src/Plugin/Block/FieldBlock.php \Drupal\layout_builder\Plugin\Block\FieldBlock::build()

Builds and returns the renderable array for this block plugin.

If a block should not be rendered because it has no content, then this method must also ensure to return no content: it must then only return an empty array, or an empty array with #cache set (with cacheability metadata indicating the circumstances for it being empty).

Return value

array A renderable array representing the content of the block.

Overrides BlockPluginInterface::build

See also

\Drupal\block\BlockViewBuilder

File

core/modules/layout_builder/src/Plugin/Block/FieldBlock.php, line 157

Class

FieldBlock
Provides a block that renders a field from an entity.

Namespace

Drupal\layout_builder\Plugin\Block

Code

public function build() {
  $display_settings = $this
    ->getConfiguration()['formatter'];
  $display_settings['third_party_settings']['layout_builder']['view_mode'] = $this
    ->getContextValue('view_mode');
  $entity = $this
    ->getEntity();
  try {
    $build = $entity
      ->get($this->fieldName)
      ->view($display_settings);
  } catch (EnforcedResponseException $e) {
    throw $e;
  } catch (\Exception $e) {
    $build = [];
    $this->logger
      ->warning('The field "%field" failed to render with the error of "%error".', [
      '%field' => $this->fieldName,
      '%error' => $e
        ->getMessage(),
    ]);
  }
  CacheableMetadata::createFromRenderArray($build)
    ->addCacheableDependency($this)
    ->applyTo($build);
  return $build;
}