You are here

public function SocialMediaFormatter::viewElements in Social media share 8

Builds a renderable array for a field value.

Parameters

\Drupal\Core\Field\FieldItemListInterface $items: The field values to be rendered.

string $langcode: The language that should be used to render the field.

Return value

array A renderable array for $items, as an array of child elements keyed by consecutive numeric indexes starting from 0.

Overrides FormatterInterface::viewElements

File

src/Plugin/Field/FieldFormatter/SocialMediaFormatter.php, line 53

Class

SocialMediaFormatter
Plugin implementation of the 'field_example_simple_text' formatter.

Namespace

Drupal\social_media\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];
  foreach ($items as $delta => $item) {
    $config = [];
    $block_instance = $this->blockManager
      ->createInstance('social_sharing_block', $config);

    // Some blocks might implement access check.
    $access_result = $block_instance
      ->access(\Drupal::currentUser());

    // Return empty render array if user doesn't have access.
    // $access_result can be boolean or an AccessResult class.
    if (is_object($access_result) && $access_result
      ->isForbidden() || is_bool($access_result) && !$access_result) {
      return [];
    }
    $elements[$delta] = [
      '#theme' => 'block',
      '#attributes' => [],
      '#configuration' => $block_instance
        ->getConfiguration(),
      '#plugin_id' => $block_instance
        ->getPluginId(),
      '#base_plugin_id' => $block_instance
        ->getBaseId(),
      '#derivative_plugin_id' => $block_instance
        ->getDerivativeId(),
      'content' => $block_instance
        ->build(),
    ];
  }
  return $elements;
}