Inserts a default value for each entity field not having one.
\Drupal\Core\Entity\EntityInterface $entity: The entity for the operation.
string $langcode: (optional) The field language code to fill-in with the default value. Defaults to the entity language.
function field_populate_default_values(EntityInterface $entity, $langcode = NULL) {
// Ensure we are working with a BC mode entity.
$entity = $entity
->getBCEntity();
$entity_type = $entity
->entityType();
$langcode = $langcode ?: $entity
->language()->langcode;
foreach (field_info_instances($entity_type, $entity
->bundle()) as $field_name => $instance) {
$field = field_info_field($field_name);
$field_langcode = field_is_translatable($entity_type, $field) ? $langcode : Language::LANGCODE_NOT_SPECIFIED;
// We need to preserve existing values.
if (empty($entity->{$field_name}) || !array_key_exists($field_langcode, $entity->{$field_name})) {
$items = field_get_default_value($entity, $field, $instance, $field_langcode);
if (!empty($items)) {
$entity->{$field_name}[$field_langcode] = $items;
}
}
}
}