You are here

public function DisqusFormatter::viewElements in Disqus 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/DisqusFormatter.php, line 73

Class

DisqusFormatter
Provides a default disqus comment formatter.

Namespace

Drupal\disqus\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $element = [];

  // As the Field API only applies the "field default value" to newly created
  // entities, we'll apply the default value for existing entities.
  if ($items
    ->count() == 0) {
    $field_default_value = $items
      ->getFieldDefinition()
      ->getDefaultValue($items
      ->getEntity());
    if (!empty($field_default_value)) {
      $items->status = $field_default_value[0]['status'];
    }
  }
  if ($items->status == 1 && $this->currentUser
    ->hasPermission('view disqus comments')) {
    $element[] = [
      '#type' => 'disqus',
      '#title' => (string) $items
        ->getEntity()
        ->label(),
    ];
    $node = $items
      ->getEntity();
    if (!$node
      ->isNew() || !$node->in_preview) {
      $element[0] += [
        '#url' => $node
          ->toUrl('canonical', [
          'absolute' => TRUE,
        ])
          ->toString(),
      ];
      $element[0] += [
        '#identifier' => $items->identifier ?: "{$node->getEntityTypeId()}/{$node->id()}",
      ];
    }
  }
  return $element;
}