You are here

protected static function EntityCreationTrait::getOrCreateEntity in Select2 Boxes 8

Get an entity by its properties, or create it if it doesn't exist.

Parameters

string $entity_type_id: Target entity type ID.

array $values: Values of the entity (eg. label, bundle).

Return value

\Drupal\Core\Entity\EntityInterface|null The matching or newly created entity.

Throws

\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException

\Drupal\Core\Entity\EntityStorageException

\Drupal\Component\Plugin\Exception\PluginNotFoundException

1 call to EntityCreationTrait::getOrCreateEntity()
AutoCreationProcessTrait::processValueItem in src/AutoCreationProcessTrait.php
Process value item.

File

src/EntityCreationTrait.php, line 47

Class

EntityCreationTrait
Trait EntityCreationTrait.

Namespace

Drupal\select2boxes

Code

protected static function getOrCreateEntity($entity_type_id, array $values) {

  // Prepare entity storage handler.
  $storage = self::getEntityStorage($entity_type_id);

  // Check for an existing entity.
  $entities = $storage
    ->loadByProperties($values);
  if (!empty($entities)) {

    // Found some matches - just use the first one.
    $entity = reset($entities);
  }
  else {

    // No entity has been found - so create it.
    $entity = $storage
      ->create($values);
    $entity
      ->save();
  }
  return $entity;
}