I require a computed Dynamic Entity Reference field. An example of how one can create such a thing:

namespace Drupal\my_module\Plugin\Field;

use Drupal\dynamic_entity_reference\Plugin\Field\FieldType\DynamicEntityReferenceFieldItemList;
use Drupal\Core\TypedData\ComputedItemListTrait;

/**
 * A computed Dynamic Entity Reference field.
 */
class MyComputedDERFieldFieldItemList extends DynamicEntityReferenceFieldItemList {

  use ComputedItemListTrait;

  /**
   * {@inheritdoc}
   */
  protected function computeValue() {
    $entity = $this->getEntity();

    // This would be something computed.
    $this->list[0] = $this->createItem(0, [
      'target_type' => 'node',
      'target_id' => 123,
    ]);

    // This would be something computed.
    $this->list[1] = $this->createItem(1, [
      'target_type' => 'user',
      'target_id' => 456,
    ]);
  }

}

\Drupal\dynamic_entity_reference\Plugin\Field\FieldType\DynamicEntityReferenceFieldItemList::referencedEntities() will always return an empty array of this however. This is because the check if the field is empty or not is incorrect:

  /**
   * {@inheritdoc}
   */
  public function referencedEntities() {
    if (empty($this->list)) {
      return [];
    }
    
    ...
  }

should be using the isEmpty() function. Thus:

  /**
   * {@inheritdoc}
   */
  public function referencedEntities() {
    if ($this->isEmpty()) {
      return [];
    }
    
    ...
  }

FYI: \Drupal\Core\Field\EntityReferenceFieldItemList::referencedEntities() uses isEmpty() as well.

Comments

rp7 created an issue. See original summary.

rp7’s picture

Patch attached changes the check to isEmpty() .

rp7’s picture

Status: Active » Needs review
jibran’s picture

Status: Needs review » Reviewed & tested by the community
Related issues: +#2978848: EntityReferenceFieldItemList::referencedEntities() doesn't work for computed fields

Thanks!

  • jibran committed 7850be9 on 8.x-1.x authored by rp7
    Issue #3006208 by rp7: DER referencedEntities() does not support...

  • jibran committed fd816b4 on 8.x-2.x authored by rp7
    Issue #3006208 by rp7: DER referencedEntities() does not support...
jibran’s picture

Status: Reviewed & tested by the community » Fixed

Committed and pushed to both 8.x-1.x and 8.x-2.x.

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.