function EntityReferenceFieldItemList::processDefaultValue

Same name in other branches
  1. 9 core/lib/Drupal/Core/Field/EntityReferenceFieldItemList.php \Drupal\Core\Field\EntityReferenceFieldItemList::processDefaultValue()
  2. 10 core/lib/Drupal/Core/Field/EntityReferenceFieldItemList.php \Drupal\Core\Field\EntityReferenceFieldItemList::processDefaultValue()
  3. 11.x core/lib/Drupal/Core/Field/EntityReferenceFieldItemList.php \Drupal\Core\Field\EntityReferenceFieldItemList::processDefaultValue()

Overrides FieldItemList::processDefaultValue

File

core/lib/Drupal/Core/Field/EntityReferenceFieldItemList.php, line 62

Class

EntityReferenceFieldItemList
Defines a item list class for entity reference fields.

Namespace

Drupal\Core\Field

Code

public static function processDefaultValue($default_value, FieldableEntityInterface $entity, FieldDefinitionInterface $definition) {
    $default_value = parent::processDefaultValue($default_value, $entity, $definition);
    if ($default_value) {
        // Convert UUIDs to numeric IDs.
        $uuids = [];
        foreach ($default_value as $delta => $properties) {
            if (isset($properties['target_uuid'])) {
                $uuids[$delta] = $properties['target_uuid'];
            }
        }
        if ($uuids) {
            $target_type = $definition->getSetting('target_type');
            $entity_ids = \Drupal::entityQuery($target_type)->condition('uuid', $uuids, 'IN')
                ->execute();
            $entities = \Drupal::entityTypeManager()->getStorage($target_type)
                ->loadMultiple($entity_ids);
            $entity_uuids = [];
            foreach ($entities as $id => $entity) {
                $entity_uuids[$entity->uuid()] = $id;
            }
            foreach ($uuids as $delta => $uuid) {
                if (isset($entity_uuids[$uuid])) {
                    $default_value[$delta]['target_id'] = $entity_uuids[$uuid];
                    unset($default_value[$delta]['target_uuid']);
                }
                else {
                    unset($default_value[$delta]);
                }
            }
        }
        // Ensure we return consecutive deltas, in case we removed unknown UUIDs.
        $default_value = array_values($default_value);
    }
    return $default_value;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.