function ContentEntityStorageBase::createWithSampleValues

Same name in other branches
  1. 9 core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php \Drupal\Core\Entity\ContentEntityStorageBase::createWithSampleValues()
  2. 8.9.x core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php \Drupal\Core\Entity\ContentEntityStorageBase::createWithSampleValues()
  3. 11.x core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php \Drupal\Core\Entity\ContentEntityStorageBase::createWithSampleValues()

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 220

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

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