A default value can be set for fields that are attached to a content type (i.e., any field-able entity). The entered value is used to pre-fill the form (i.e., entity) when creating new content. Although having a static starting value is often perfectly fine, true power comes when these values can be set dynamically. Of course, you accomplish this by using hook_form_alter
or hook_field_widget_multivalue_form_alter
, but these only fulfill when content is created using forms. Therefore, the recommended way is to implement a function to provide the value and set the function's name in field.field.<entity_type>.<bundle_name>.<field_name>.yml
for the default_value_callback
setting.
…
translatable: false
default_value: { }
default_value_callback: example_default_value
settings: { }
field_type: string
…
The code below illustrates an example of the default value callback function. Here we simply return a (translated) string, but the value can, of course, be provided using more complex logic, e.g., based on the entity type/bundle or even using a service to get values from external API. The sky is the limit!
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
/**
* Delivers the default value for the example field.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* The entity being created.
* @param \Drupal\Core\Field\FieldDefinitionInterface $definition
* The field definition.
*
* @return array
* Array providing, for each delta item, initial values for the field's
* properties.
*
* @see \Drupal\Core\Field\FieldConfigBase::getDefaultValue()
*/
function example_default_value(ContentEntityInterface $entity, FieldDefinitionInterface $definition) {
// Maybe some logic here, to create the values dynamically or even retrieve
// the values from an external source.
return [
['value' => t('Some value')],
];
}
Don't forget to import the configuration after setting the default_value_callback
and rebuild Drupal's caches in order for the function to be found.
Category
Drupal
Field
Comments