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.
| Comment | File | Size | Author |
|---|---|---|---|
| #2 | dynamic_entity_reference-computed_referenced_entities-3006208-2.patch | 605 bytes | rp7 |
Comments
Comment #2
rp7 commentedPatch attached changes the check to
isEmpty().Comment #3
rp7 commentedComment #4
jibranThanks!
Comment #7
jibranCommitted and pushed to both 8.x-1.x and 8.x-2.x.