datafield-1.x-dev/src/Plugin/DataField/FieldFormatter/EntityReferenceIdFormatter.php

src/Plugin/DataField/FieldFormatter/EntityReferenceIdFormatter.php
<?php

namespace Drupal\datafield\Plugin\DataField\FieldFormatter;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\Attribute\FieldFormatter;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\datafield\Plugin\DataFieldFormatterInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Plugin implementation of the 'entity reference ID' formatter.
 */
#[FieldFormatter(
  id: 'entity_reference_entity_id',
  label: new TranslatableMarkup('Entity ID'),
  description: new TranslatableMarkup('Display the ID of the referenced entities.'),
  field_types: ['entity_reference'],
)]
class EntityReferenceIdFormatter implements DataFieldFormatterInterface, ContainerFactoryPluginInterface {

  /**
   * Constructs a UrlPlainFormatter object.
   *
   * @param string $plugin_id
   *   The plugin_id for the formatter.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param mixed $field_definition
   *   The definition of the field to which the formatter is associated.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   The entity type manager.
   */
  public function __construct($plugin_id, $plugin_definition, $field_definition, protected EntityTypeManagerInterface $entityTypeManager) {
    unset($plugin_id, $plugin_definition, $field_definition);
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $plugin_id,
      $plugin_definition,
      $configuration,
      $container->get('entity_type.manager'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function viewElements($item, $langcode) {
    if (empty($item->value)) {
      return $item->value;
    }
    $explode = explode(':', $item->field_setting["entity_reference_type"]);
    $reference_type = end($explode);
    $entity_id = $item->value;
    $entity = $this->entityTypeManager->getStorage($reference_type)->load($entity_id);
    if (empty($entity)) {
      return $item->value;
    }
    return [
      '#plain_text' => $entity->id(),
      '#langcode' => $langcode,
      '#cache' => [
        'tags' => $entity->getCacheTags(),
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary($settings = []) {
    return [];
  }

}

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

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