function field_populate_default_values

Inserts a default value for each entity field not having one.

Parameters

\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.

Related topics

1 call to field_populate_default_values()
field_entity_create in drupal/core/modules/field/field.module
Implements hook_entity_create().

File

drupal/core/modules/field/field.module, line 271
Attach custom data fields to Drupal entities.

Code

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;
      }
    }
  }
}