Add UUID formatter

Created on 12 November 2022, about 2 years ago
Updated 23 March 2023, over 1 year ago

I know this is completely the wrong way to deliver this but the contents of this code block placed into a file src/Plugin/Field/FieldFormatter/MediaUUID.php provides a field formatter which displays the UUID of a media item. It works here :) could probably drop the use...File? Thanks for making this module.

<?php

namespace Drupal\media_field_formatters\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceFormatterBase;
use Drupal\file\Entity\File;
use Drupal\media\MediaInterface;

/**
 * Plugin implementation of the 'media_uuid' formatter.
 *
 * @FieldFormatter(
 *   id = "media_uuid",
 *   label = @Translation("UUID of media object"),
 *   field_types = {
 *     "entity_reference"
 *   }
 * )
 */
class MediaUUID extends EntityReferenceFormatterBase {

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

    // Early opt-out if the field is empty.
    if (empty($media_items)) {
      return $elements;
    }

    /** @var \Drupal\media\MediaInterface[] $media_items */
    foreach ($media_items as $delta => $media) {
      // Only handle media objects.
      if ($media instanceof MediaInterface) {
        // Get the value from the source field.
        $value = $media->uuid();

        $elements[$delta] = [
          // '#markup' => $media->getSource()->getSourceFieldValue($media),
          '#type' => 'inline_template',
          '#template' => '{{ value|raw }}',
          '#context' => [
            'value' => $value,
          ],
        ];

        // Add cacheability of each item in the field.
        // $this->renderer->addCacheableDependency($elements[$delta], $media);
      }
    }

    return $elements;
  }

}
✨ Feature request
Status

Fixed

Version

1.0

Component

Code

Created by

πŸ‡ΊπŸ‡ΈUnited States hyperlogos

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024