You are here

public function ContentEntityStorageBase::createWithSampleValues in Drupal 9

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php \Drupal\Core\Entity\ContentEntityStorageBase::createWithSampleValues()

Creates an entity with sample field values.

Parameters

string|bool $bundle: (optional) The entity bundle.

array $values: (optional) Any default values to use during generation.

Return value

\Drupal\Core\Entity\FieldableEntityInterface A fieldable content entity.

Throws

\Drupal\Core\Entity\EntityStorageException Thrown if the bundle does not exist or was needed but not specified.

Overrides ContentEntityStorageInterface::createWithSampleValues

1 call to ContentEntityStorageBase::createWithSampleValues()
PathAliasStorage::createWithSampleValues in core/modules/path_alias/src/PathAliasStorage.php
Creates an entity with sample field values.
1 method overrides ContentEntityStorageBase::createWithSampleValues()
PathAliasStorage::createWithSampleValues in core/modules/path_alias/src/PathAliasStorage.php
Creates an entity with sample field values.

File

core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php, line 126

Class

ContentEntityStorageBase
Base class for content entity storage handlers.

Namespace

Drupal\Core\Entity

Code

public function createWithSampleValues($bundle = FALSE, array $values = []) {

  // ID and revision should never have sample values generated for them.
  $forbidden_keys = [
    $this->entityType
      ->getKey('id'),
  ];
  if ($revision_key = $this->entityType
    ->getKey('revision')) {
    $forbidden_keys[] = $revision_key;
  }
  if ($bundle_key = $this->entityType
    ->getKey('bundle')) {
    if (!$bundle) {
      throw new EntityStorageException("No entity bundle was specified");
    }
    if (!array_key_exists($bundle, $this->entityTypeBundleInfo
      ->getBundleInfo($this->entityTypeId))) {
      throw new EntityStorageException(sprintf("Missing entity bundle. The \"%s\" bundle does not exist", $bundle));
    }
    $values[$bundle_key] = $bundle;

    // Bundle is already set
    $forbidden_keys[] = $bundle_key;
  }

  // Forbid sample generation on any keys whose values were submitted.
  $forbidden_keys = array_merge($forbidden_keys, array_keys($values));

  /** @var \Drupal\Core\Entity\FieldableEntityInterface $entity */
  $entity = $this
    ->create($values);
  foreach ($entity as $field_name => $value) {
    if (!in_array($field_name, $forbidden_keys, TRUE)) {
      $entity
        ->get($field_name)
        ->generateSampleItems();
    }
  }
  return $entity;
}