I wanted to modify some of the logged values during an entity pre-save for Entity Logs and I ran into an issue.
When calling setEntityLoggedId()
if you pass in an entity ID (as the method name and signature imply you should) an exception gets thrown during saving:
The website encountered an unexpected error. Please try again later.
Error: Call to a member function getEntityTypeId() on null in Drupal\dynamic_entity_reference\Plugin\Field\FieldType\DynamicEntityReferenceItem->onChange() (line 133 of modules/contrib/dynamic_entity_reference/src/Plugin/Field/FieldType/DynamicEntityReferenceItem.php).
Drupal\dynamic_entity_reference\Plugin\Field\FieldType\DynamicEntityReferenceItem->onChange('entity', ) (Line: 128)
Drupal\Core\TypedData\Plugin\DataType\Map->set('entity', '9', ) (Line: 408)
Drupal\dynamic_entity_reference\Plugin\Field\FieldType\DynamicEntityReferenceItem->setValue('9', ) (Line: 69)
Drupal\Core\TypedData\Plugin\DataType\ItemList->setValue(Array, 1) (Line: 107)
Drupal\Core\Field\FieldItemList->setValue(Array, 1) (Line: 627)
Drupal\Core\Entity\ContentEntityBase->set('entity_logged_id', '9') (Line: 158)
Drupal\entity_log\Entity\EntityLog->setEntityLoggedId('9') (Line: 167)
What does work however is passing in a loaded entity object into setEntityLoggedId()
.
I am not 100% familiar with drupal's handling of custom entities, but I beleive the entity_logged_id
property which is set up as a dynamic_entity_reference
in EntityLog::baseFieldDefinitions()
has core handle the parsing of the entities to split up the entity type and ID in the tables created.
If you have a look at the entity_log
db table, it shows two columns derived from this property: entity_logged_id__target_id
and entity_logged_id__target_type
.
Also note the logic in EntityLogService::logFields()
sets the entity_logged_id
property to the full entity.
So all this begs the question of what needs to be done from here.
First of all I beleive that setEntityLoggedId()
should either be removed or deprecated, then add a setEntityLogged()
method with the same logic as setEntityLoggedId()
but with an EntityInterface
parameter in place of the integer parameter.
All the following suggestions I would consider optional since they require heavy refactoring:
- Rename the
entity_logged_id
property to entity_logged
and add an update script to handle data migration.
- Remove the
log_type
property and associated methods as it is redundant to the logged entity's type