Allow field_type = "image"

Created on 25 August 2023, about 1 year ago
Updated 28 August 2023, about 1 year ago

Problem/Motivation

In my current project, I have a Node, with an Term reference.
I use ui_patterns to display this node and I need to destructure fields from Term in this template.

I have two fields (term_name and term_image)

For the name, no problem, a single value computed fields works great.
But for the image, when addind in the annotation field_type = "image", i have a nice error

TypeError: Drupal\image\Plugin\Field\FieldFormatter\ImageFormatterBase::getEntitiesToView(): Argument #1 ($items) must be of type Drupal\Core\Field\EntityReferenceFieldItemListInterface, Drupal\computed_field\Field\ComputedFieldClass given, called in /var/www/html/web/core/modules/image/src/Plugin/Field/FieldFormatter/ImageFormatter.php on line 214 in Drupal\image\Plugin\Field\FieldFormatter\ImageFormatterBase->getEntitiesToView() (line 17 of core/modules/image/src/Plugin/Field/FieldFormatter/ImageFormatterBase.php). 

Proposed resolution

With the attached patch, it now works, images are considered as references.

Here's my plugin :

<?php

namespace Drupal\xxx_core\Plugin\ComputedField;

use Drupal\computed_field\Field\ComputedFieldDefinitionWithValuePluginInterface;
use Drupal\computed_field\Plugin\ComputedField\ComputedFieldBase;
use Drupal\computed_field\Plugin\ComputedField\SingleValueTrait;
use Drupal\Core\Entity\EntityInterface;

/**
 * @ComputedField(
 *   id = "attached_company_logo",
 *   label = @Translation("Company logo"),
 *   field_type = "image",
 *   attach = {
 *     "scope" = "base",
 *     "field_name" = "company_logo",
 *     "entity_types" = {
 *       "programme" = {},
 *     },
 *   },
 * )
 */
class AttachedCompanyLogo extends ComputedFieldBase {

  use SingleValueTrait;

  public function singleComputeValue(EntityInterface $host_entity, ComputedFieldDefinitionWithValuePluginInterface $computed_field_definition): mixed {
    return $host_entity->get('field_promoteur')->entity->get('field_logo')->entity->id();
  }
}
🐛 Bug report
Status

Fixed

Version

4.0

Component

Code

Created by

🇫🇷France Guillaume Aveline

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

Comments & Activities

Production build 0.71.5 2024