Problem/Motivation
When calling EntityReferenceFieldItemList::referencedEntities()
the returned entities never end up in the actual field items of the field item list. This can cause strange an unexpected behavior.
One example is when working with Entity Reference Revisions' EntityNeedsSaveInterface
. You can call setNeedsSave(TRUE)
on the entities returned from referencedEntities()
but they will still not actually be saved.
For example:
$items = $host_entity->get('entity_reference_field');
foreach ($items->referencedEntities() as $referenced_entity) {
$referenced_entity->setNeedsSave(TRUE);
}
$host->save();
// The referenced entities have *not* been saved!
// In order to achieve this, one must manually set the entity property
// of the respective field items.
foreach ($items->referencedEntities() as $delta => $referenced_entity) {
$referenced_entity->setNeedsSave(TRUE);
$items->get($delta)->set('entity', $referenced_entity);
}
$host->save();
// This time the referenced entities *have* been saved.
Note that this is - in a way - the "reverse" of #2826717: EntityReferenceFieldItemList::referencedEntities might not return up-to-date entity objects: There the problem is that referencedEntities()
ignores the entity
property if it is already set, this is about referencedEntities()
not setting it if it is not yet set.
Proposed resolution
Set the entity
property of each field item in EntityReferenceFieldItem::referencedEntities()
.
Remaining tasks
?
User interface changes
None.
API changes
None?
Data model changes
None.
Comments
Comment #2
tstoecklerFix PHP formatting
Comment #3
tstoecklerExpand example code
Comment #4
BerdirI assume that is only a problem for entity types that don't have a static cache?
Comment #5
hchonovThe problem exists for entity types that do not have a static cache but also for ones that have static cache, because during the process somewhere $storage->resetCache might be called, or when an entity is saved it is thrown away from the static cache as well ...