You are here

public static function CivicrmEntity::preCreate in CiviCRM Entity 8.3

Changes the values of an entity before it is created.

Load defaults for example.

Parameters

\Drupal\Core\Entity\EntityStorageInterface $storage: The entity storage object.

mixed[] $values: An array of values to set, keyed by property name. If the entity type has bundles the bundle key has to be specified.

Overrides EntityBase::preCreate

File

src/Entity/CivicrmEntity.php, line 72

Class

CivicrmEntity
Entity class for CiviCRM entities.

Namespace

Drupal\civicrm_entity\Entity

Code

public static function preCreate(EntityStorageInterface $storage, array &$values) {

  // If the `bundle` property is missing during the create operation, Drupal
  // will error – even if our bundle is computed on other required fields.
  // This ensures the values array has the bundle property set.
  $entity_type = $storage
    ->getEntityType();
  if ($entity_type
    ->hasKey('bundle')) {
    $bundle_property = $entity_type
      ->get('civicrm_bundle_property');

    /** @var \Drupal\civicrm_entity\CiviCrmApiInterface $civicrm_api */
    $civicrm_api = \Drupal::service('civicrm_entity.api');
    $options = $civicrm_api
      ->getOptions($entity_type
      ->get('civicrm_entity'), $bundle_property);
    if (isset($values[$entity_type
      ->getKey('bundle')]) && $values[$entity_type
      ->getKey('bundle')] === $entity_type
      ->id()) {
      $raw_bundle_value = key($options);
    }
    else {
      $raw_bundle_value = $values[$bundle_property];
    }
    $bundle_value = $options[$raw_bundle_value];
    $transliteration = \Drupal::transliteration();
    $machine_name = SupportedEntities::optionToMachineName($bundle_value, $transliteration);
    $values[$entity_type
      ->getKey('bundle')] = $machine_name;
  }
}