I've created a custom entity. One of the fields I've added is an entity reference field that was created calling BaseFieldDefinition::setRequired(FALSE)
. When I installed my module and tried to add a new instance of my custom entity, I got an error when that field was not set, even though it was defined as not required.
For reference, this is the field definition I'm using.
$fields['publisher'] = BaseFieldDefinition::create('entity_reference')
->setLabel(t('Publisher'))
->setRequired(FALSE)
->setSetting('target_type', 'taxonomy_term')
->setSetting('handler', 'default:taxonomy_term')
->setSetting('handler_settings', array(
'target_bundles' => array(
'publisher' => 'publisher'
),
// 'sort' => array(
// 'field' => 'name'
// )
))
->setDisplayOptions('view', array(
'label' => 'hidden',
'type' => 'author',
'weight' => 0,
))
->setDisplayOptions('form', array(
'title' => t('Pubs'),
'type' => 'options_select',
'weight' => 4,
))
->setDisplayConfigurable('form', TRUE)
->setDisplayConfigurable('view', TRUE);
This is the error I got.
Drupal\Core\Entity\EntityStorageException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'publisher' cannot be null: INSERT INTO "series"...
The database table for this custom entity contains the following fields.
It's evident that, even though this field has been created calling setRequired(FALSE)
, it must be set.
To solve this issue, I found that I can manually update my database table's properties so that the field's 'Null' property is set to 'Yes', though this is clearly not a preferred approach.
Then I found How do I allow an entity reference to be null in my custom entity? where one of the answer states that fields included in the entity_keys annotation must be set, regardless of the value set with setRequired()
.
Where is this kind of information documented?
This isn't documented in Creating a content entity type in Drupal 8. In fact, I had the impression it was mandatory to list all the fields in this annotation array.