You are here

public function LikeDislikeFormatter::viewElements in Like/Dislike 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/LikeDislikeFormatter.php, line 118

Class

LikeDislikeFormatter
Plugin implementation of the 'like_dislike_formatter' formatter.

Namespace

Drupal\like_dislike\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode = 'en') {
  $entity = $items
    ->getEntity();
  $elements = [];

  // Data to be passed in the url.
  $initial_data = [
    'entity_type' => $entity
      ->getEntityTypeId(),
    'entity_id' => $entity
      ->id(),
    'field_name' => $items
      ->getFieldDefinition()
      ->getName(),
  ];
  foreach ($items as $delta => $item) {
    $initial_data['likes'] = $items[$delta]->likes;
    $initial_data['dislikes'] = $items[$delta]->dislikes;
  }
  $data = base64_encode(json_encode($initial_data));
  $like_url = Url::fromRoute('like_dislike.manager', [
    'clicked' => 'like',
    'data' => $data,
  ])
    ->toString();
  $dislike_url = Url::fromRoute('like_dislike.manager', [
    'clicked' => 'dislike',
    'data' => $data,
  ])
    ->toString();

  // If user is anonymous, then append the destination back url.
  $user = $this->currentUser
    ->id();
  $destination = '';
  if ($user == 0) {
    $destination = '?like-dislike-redirect=' . $this->requestStack
      ->getCurrentRequest()
      ->getUri();
  }
  $elements[] = [
    '#theme' => 'like_dislike',
    '#likes' => $initial_data['likes'],
    '#dislikes' => $initial_data['dislikes'],
    '#like_url' => $like_url . $destination,
    '#dislike_url' => $dislike_url . $destination,
    '#entity_id' => $initial_data['entity_id'],
  ];
  $elements['#attached']['library'][] = 'core/drupal.ajax';
  $elements['#attached']['library'][] = 'like_dislike/like_dislike';

  // Set the cache for the element.
  $elements['#cache']['max-age'] = 0;
  return $elements;
}