1

I have a custom revisionable entity with a few dozen fields. I'm importing data about the entity on a periodic basis. If the entity has changed, I'd like to save it and create a new revision.

$dogs = \Drupal::entityTypeManager()
  ->getStorage('my_entity')
  ->loadByProperties(['my_entity_id' => $my_entity_id]);

$dog = reset($dogs);

$dog->set('name', $record['TheName']);
$dog->set('birth_date', $record['Dog Birth Date']);
// Lots more ->set happening here.
$dog->set('notes', $record['Notes']);
if ($dog->someMagicComparisonFunction()) {
  $dog->setNewRevision(TRUE);
  $dog->save();
}

I searched for the someMagicComparisonFunction but didn't find it. Does it exist?

1

1 Answer 1

2

This may do the trick in a hook_entity_presave(), or get you close:

$old_dog = clone $dog;
update_the_dog($dog);

// Use == to allow for out of order keys.
$same = $dog->toArray() == $old_dog->toArray();

This is kinda of cheating, and you may want to filter the arrays for just the fields and not the properties. It also isn't multilingual-safe.

To do it properly, start reading ContentEntityBase::hasTranslationChanges() and FieldItemList::equals(). The code above makes a lot of assumptions about fields and storage, which ContentEntityBase() does properly.

3
  • 1
    The shown code works also outside of hook_entity_presave().
    – avpaderno
    Commented May 21, 2019 at 7:02
  • Thanks! I think the comparison should be != if the variable is $changed. This comparison is testing more for a $same - right?
    – greggles
    Commented May 21, 2019 at 17:03
  • @greggles Yeah, updated the var name in the code.
    – mpdonadio
    Commented May 21, 2019 at 17:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.