EntityReferenceFieldItemList::processDefaultValue

public static EntityReferenceFieldItemList::processDefaultValue($default_value, FieldableEntityInterface $entity, FieldDefinitionInterface $definition)

Processes the default value before being applied.

Defined or configured default values of a field might need some processing in order to be a valid runtime value for the field type; e.g., a date field could process the defined value of 'NOW' to a valid date.

Parameters

array $default_value: The unprocessed default value defined for the field, as a numerically indexed array of items, each item being an array of property/value pairs.

\Drupal\Core\Entity\FieldableEntityInterface $entity: The entity for which the default value is generated.

\Drupal\Core\Field\FieldDefinitionInterface $definition: The definition of the field.

Return value

array The return default value for the field.

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 = array();
    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::entityManager()
        ->getStorage($target_type)
        ->loadMultiple($entity_ids);

      $entity_uuids = array();
      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;
}
doc_Drupal
2016-10-29 09:07:21
Comments
Leave a Comment

Please login to continue.