I have discovered, that function Drupal\Core\Entity\EntityDefinitionUpdateManager::installFieldStorageDefinition()
ignores initial_value
data, when creating new field using MySQL driver (other drivers not checked yet).
As result, MySQL table field got empty DEFAULT value, instead of value from FieldStorageDefinition
, that was set using function setInitialValue()
.
1. Create new FieldStorageDefinition with some initial value, something like this:
$field_storage_definitions['test_initial_value] = BaseFieldDefinition::create('integer')
->setInitialValue(23);
2. Launch xdebug, make a breakpoint at place, where MySQL driver must add the DEFAULT 23
to query:
https://git.drupalcode.org/project/drupal/-/blob/9.2.x/core/lib/Drupal/C...
protected function createFieldSql($name, $spec) {
...
if (array_key_exists('default', $spec)) {
$sql .= ' DEFAULT ' . $this->escapeDefaultValue($spec['default']);
}
3. Try to create field with this definition with started debugger:
$definition_update_manager = \Drupal::entityDefinitionUpdateManager();
$definition_update_manager->installFieldStorageDefinition('test_initial_value', 'node', 'node', $field_storage_definition);
4. When xdebug stops on breakpoint - lookup at value of variable $spec
, you will see:
array (
'type' => 'int',
'unsigned' => false,
'size' => 'normal',
'not null' => false,
'initial' => 23,
'mysql_type' => 'INT',
)
The problem is that initial value "23", that we fill before via setInitialValue(23)
located in 'initial' key, but function createFieldSql() lookups this value in 'default' key of this array, as we see in code snippet from step 2.
5. As result, field will be successfully added to `node_field_data` table, but will have NULL default value, instead '23':
`test_initial_value` int(11) DEFAULT NULL
6. Let's also create and save the new node entity, and lookup the value of this field in database table cell, you will see NULL instead of 23 too.
This looks like divergence with key names for pass initial values - initial
vs default
, so we must select one of them and update code to use it, instead of two different variants.
Is my assumption right, or this is correct behavior? If correct, can you please show me the working code snippet with setting default value to base field?
Not all content is available!
It's likely this issue predates Contrib.social: some issue and comment data are missing.