Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
Motivation
Referenced entities that are updated when the parent entity is updated should be saved as well.
Currently modules such as inline_entity_form need to jump through hoops to achieve such goal.
Proposed resolution
In the preSave method of \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem
test if the referenced entity was updated, and if so save it.
/**
* {@inheritdoc}
*/
public function preSave() {
if ($this->hasNewEntity()) {
// Save the entity if it has not already been saved by some other code.
if ($this->entity->isNew()) {
$this->entity->save();
}
else {
$storage = \Drupal::entityTypeManager()->getStorage($this->entity->getEntityTypeId());
$original = $storage->loadUnchanged($this->entity->id());
if ($original->toArray() !== $this->entity->toArray()) {
$this->entity->save();
}
}
// Make sure the parent knows we are updating this property so it can
// react properly.
$this->target_id = $this->entity->id();
}
if (!$this->isEmpty() && $this->target_id === NULL) {
$this->target_id = $this->entity->id();
}
}
User interface changes
No change
API changes
No API change
Data model changes
No change
Comments
Comment #2
amateescu CreditAttribution: amateescu for Pfizer, Inc. commentedThe
else
part of this code can never be reached, because of the surroundingif ($this->hasNewEntity()) {}
, which already checks if$this->entity
is new, see\Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::hasNewEntity
.So the only way to do this would be to have a special flag on the field item, something like
targetEntityNeedsSave
.Comment #5
jibranMoving to right component
Comment #6
BerdirEntityReferenceRevision provides and uses \Drupal\entity_reference_revisions\EntityNeedsSaveInterface for this, it however relies on explicitly setting that, it doesn't do it automatically.
I think that would help IEF a lot if it could rely on that. This allows us to make preview work with paragraphs and preventing repeated saving.