function FieldBlock::build

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()
  2. 8.9.x core/modules/layout_builder/src/Plugin/Block/FieldBlock.php \Drupal\layout_builder\Plugin\Block\FieldBlock::build()
  3. 11.x 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

File

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

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 = [];
    $view = $entity->get($this->fieldName)
      ->view($display_settings);
    if ($view) {
      $build = [
        $view,
      ];
    }
  } 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;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.