The interface EntityOwnerInterface has been introduced which provides modules a generic way to identify and change the owner of an entity. Previously, this was only possible with either a hardcoded list of entity types, or by assumptions like checking for an uid field, which could lead to false positives.
What that exactly means for an entity can differ, in Core, this interface is currently implemented by nodes, comments and files.
It can for example be used for modules that create related entities with the same owner, comment and entity_reference are two examples in core that do this or to notify the owner of an entity about something.
The owner has to be a user entity, the interface provides both setters and getters for the owner user entity and the ID.
7.x
// This would also match user entities, but there the uid is the primary key and must not be changed.
if (isset($entity->uid)) {
$entity->uid = $new_owner->uid;
}
8.x
if ($entity instanceof EntityOwnerInterface) {
$entity->setOwner($new_owner);
}
Comments
Error in code samples
Unless I'm overlooking the obvious, the code samples are testing the wrong variables and should actually be as follows:
7.x
8.x
No, the entity has to
No, the entity has to implement the EntityOwnerInterface, not the user / new owner.