Change record status: 
Project: 
Introduced in branch: 
main
Introduced in version: 
12.1.0
Description: 

\Drupal\Core\TypedData\DataDefinition::setDefault() declares a default value for typed data. DataDefinitionInterface::getDefault() returns it, or NULL when no default is set.

TypedData::applyDefaultValue() now applies the declared default instead of NULL. Strings, integers and plain lists use this directly.

Maps override applyDefaultValue(): a map applies each property's default instead of its own. A field item is a map, so it gets its properties' defaults unless its field type overrides applyDefaultValue().

Declaring a property default in a field type

Set the default in propertyDefinitions():

$properties['color'] = DataDefinition::create('string')
  ->setLabel(new TranslatableMarkup('Color'))
  ->setDefault('blue');

Before this change, a new entity's field with no default value of its own got one temporary item with every property NULL. FieldItemList::applyDefaultValue() then removed it as empty. With a property default, that item can now have a value. If the field type's isEmpty() checks that property, the item is kept and saved. This applies to base fields and configurable fields that use the field type.

Field defaults are unchanged

BaseFieldDefinition inherits setDefault(), but a field's default still comes from setDefaultValue() and setDefaultValueCallback(). FieldItemList::applyDefaultValue() never reads getDefault(), so calling setDefault() on a base field does nothing.

// Use this for a field's default.
$fields['status'] = BaseFieldDefinition::create('boolean')
  ->setDefaultValue(TRUE);

Implementers

A class that implements DataDefinitionInterface without extending DataDefinition must add:

public function getDefault(): mixed {
  return NULL;
}

A DataDefinition subclass that already has its own getDefault() must add the : mixed return type. Without it, PHP throws a fatal error because the parent method now declares one.

Impacts: 
Module developers