knowledge-8.x-1.x-dev/src/Plugin/Field/FieldFormatter/AuthorNameFormatter.php

src/Plugin/Field/FieldFormatter/AuthorNameFormatter.php
<?php

namespace Drupal\knowledge\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;

/**
 * Plugin implementation of the 'knowledge_username' formatter.
 *
 * @FieldFormatter(
 *   id = "knowledge_username",
 *   label = @Translation("Author name"),
 *   description = @Translation("Display the author name."),
 *   field_types = {
 *     "string"
 *   }
 * )
 */
class AuthorNameFormatter extends FormatterBase {

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];

    foreach ($items as $delta => $item) {
      /** @var \Drupal\knowledge\KnowledgeInterface $knowledge */
      $knowledge = $item->getEntity();
      $account = $knowledge->getOwner();
      $elements[$delta] = [
        '#theme' => 'username',
        '#account' => $account,
        '#cache' => [
          'tags' => $account->getCacheTags() + $knowledge->getCacheTags(),
        ],
      ];
    }

    return $elements;
  }

  /**
   * {@inheritdoc}
   */
  public static function isApplicable(FieldDefinitionInterface $field_definition) {
    return $field_definition->getName() === 'name' && $field_definition->getTargetEntityTypeId() === 'knowledge';
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc