Custom EntityReferenceSelection label discarded and N+1

Created on 29 January 2024, 11 months ago
Updated 21 April 2024, 9 months ago

Problem/Motivation

Custom EntityReferenceSelection label overwritten by WebformEntityTrait
WebformEntityTrait::translateOptions also has an N+1 on line 143

Steps to reproduce

Create a custom EntityReferenceSelection plugin as per:


namespace Drupal\maraton\Plugin\EntityReferenceSelection;

use Drupal\Component\Utility\Html;
use Drupal\node\Plugin\EntityReferenceSelection\NodeSelection;

/**
 * Provides specific access control for the taxonomy_term entity type that has a price.
 *
 * @EntityReferenceSelection(
 *   id = "maraton:node",
 *   label = @Translation("Priced Taxonomy Term selection"),
 *   entity_types = {"node"},
 *   group = "maraton",
 *   weight = 2
 * )
 */
class PricedSelection extends NodeSelection {

  /**
   * {@inheritdoc}
   */
  public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
    $target_type = $this->getConfiguration()['target_type'];

    $query = $this->buildEntityQuery($match, $match_operator);
    if ($limit > 0) {
      $query->range(0, $limit);
    }

    $result = $query->execute();

    if (empty($result)) {
      return [];
    }

    $options = [];
    $entities = $this->entityTypeManager->getStorage($target_type)->loadMultiple($result);
    foreach ($entities as $entity_id => $entity) {
      $bundle = $entity->bundle();

      $price = 42;
      $description = $this->entityRepository->getTranslationFromContext($entity)->label() ?? '';

      $options[$bundle][$entity_id] = Html::escape(
        sprintf("%s (%.2f RON)", $description, $price)
      );
    }

    return $options;
  }
}

Create a new content type and enable translations on it
Create a webform with EntitySelect field targeting Nodes

Proposed resolution

the default NodeSelection plugin supports translations out of the box and does not have an N+1 problem

Remaining tasks

- tests?

User interface changes

- none

API changes

- none

Data model changes

- none

πŸ› Bug report
Status

Fixed

Version

6.2

Component

Code

Created by

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

Comments & Activities

Production build 0.71.5 2024