EntityOwnerTrait
can be added to entities to satisfy the requirements of EntityOwnerInterface
. In order to make use of this trait, developers must:
- Add the 'owner' entity key to the entity annotation, specifying a field name of the owner.
use Drupal\user\EntityOwnerTrait
in their entity class.- Add additional fields returned by
static::ownerBaseFieldDefinitions
to their base field list.
Examples of this trait in action can be seen on Comment, Node, File and Media.
The trait adds a default value callback `\Drupal\user\EntityOwnerTrait::getDefaultEntityOwner`, if you have been previously using a different callback, do not forget to add an update to fix exported configuration:
/**
* Updates stale references to Drupal\YOURMODULE\Entity\ENTITY_CLASS::OLD_CALLBACK.
*/
function YOURMODULE_post_update_modify_base_field_author_override() {
$uid_fields = \Drupal::entityTypeManager()
->getStorage('base_field_override')
->getQuery()
->condition('entity_type', 'ENTITY_TYPE')
->condition('field_name', 'FIELD_NAME')
->condition('default_value_callback', 'Drupal\YOURMODULE\Entity\ENTITY_CLASS::OLD_CALLBACK')
->execute();
foreach (BaseFieldOverride::loadMultiple($uid_fields) as $base_field_override) {
$base_field_override->setDefaultValueCallback('Drupal\YOURMODULE\Entity\ENTITY_CLASS::getDefaultEntityOwner')->save();
}
}
To fix this manually, export your configuration, update the callbacks and then import again. See #3153455: UID base field override configs can still have old default value callbacks for more details.
Comments
Beware - not revisionable by default
Beware - the code in
static::ownerBaseFieldDefinitions
does not currently set the owner field to be revisionable by default.If you are trying to update an existing entity type to use this, you may get hit with SQL errors like:
Uncaught PHP Exception Drupal\Core\Entity\EntityStorageException: "SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value: INSERT INTO "myentity_revision" ...
Or if you apply to a new entity type, you won't revision the owner.
The Node class actually is currently just ignoring these values, and
\Drupal\content_moderation\Entity\ContentModerationState::baseFieldDefinitions()
updates it to be revisionable.---
Work: BioRAFT