Problem/Motivation
EntityOwnerTrait provides a base field for entity types for referencing the owner of the entity.
For reasons I've not managed to figure out, this field is created on the entity base table with NOT NULL, whereas another entity reference base field doesn't get this:
CREATE TABLE `test_3260175` (
SNIP
`uid` int(10) unsigned NOT NULL COMMENT 'The ID of the target entity.',
`node` int(10) unsigned DEFAULT NULL COMMENT 'The ID of the target entity.',
SNIP
I can't see where in ownerBaseFieldDefinitions() or EntityReferenceItem this is coming from!
The presence of this NOT NULL is presumably by design, but the field definition is not set to required.
This means that if an entity type uses this trait, saving an entity in the UI with the owner field form element empty will crash: this happens on Media entity for instance (until #3260175: Saving media entity without an owner crashes is fixed).
To avoid this, all entity types which use this trait currently have to faff with doing this in their ENTITYCLASS::preSave():
// If no owner has been set explicitly, make the anonymous user the owner.
if (!$entity->getOwner()) {
$entity->setOwnerId(0);
}
Steps to reproduce
Either define a custom entity type using EntityOwnerTrait, or look at Media entities.
Proposed resolution
Making the owner field required would make sense, as internally that's what's expected, but it would impact UX as currently users can leave the owner field empty to mean 'owned by the anonymous user', which is useful behaviour.
So either:
a. make the owner field required, but add something to massage the field widget so that it can be submitted empty to be automatically set to 0
b. handle setting the at the field level, the same way that the ChangedItem field class fills in a value if it's empty:
// Set the timestamp to request time if it is not set.
if (!$this->value) {
$this->value = REQUEST_TIME;
}
Remaining tasks
Decide how to fix this
Fix it.
Comments
Comment #2
joachim commentedComment #4
berdirThe reason it's not null is because you have an entity key, and the current logic is that those fields get the not null addition. Pretty sure there are issues about that. As always, change is hard.
Node does the fall back to 0 if the owner is not valid, but it's custom to node.