You are here

function rng_update_8002 in RNG - Events and Registrations 8

Same name and namespace in other branches
  1. 8.2 rng.install \rng_update_8002()
  2. 3.x rng.install \rng_update_8002()

Convert registrant entity to one with bundles

File

./rng.install, line 98
Contains install and update functions for RNG.

Code

function rng_update_8002() {
  $entity_manager = \Drupal::entityTypeManager();
  $config_factory = \Drupal::configFactory();
  $update_manager = \Drupal::entityDefinitionUpdateManager();

  // Install 'registrant_type' config entity.
  $entity_manager
    ->clearCachedDefinitions();
  $type = $entity_manager
    ->getDefinition('registrant_type');
  $update_manager
    ->installEntityType($type);

  // Clear config cache so new registrant type saves.
  \Drupal::service('config.typed')
    ->clearCachedDefinitions();

  // Install 'type' field.
  $field_definition = \Drupal\Core\Field\BaseFieldDefinition::create('entity_reference')
    ->setLabel('Registrant type')
    ->setSetting('target_type', 'registrant_type');
  $update_manager
    ->installFieldStorageDefinition('type', 'registrant', 'registrant', $field_definition);

  // Create the first registrant_type entity which will re-capture any
  // pre-existing fields from the formerly bundle-less entity.
  $default_registrant_type_id = 'registrant';
  $registrant_type = \Drupal\rng\Entity\RegistrantType::create([
    'id' => $default_registrant_type_id,
    'label' => 'Registrant',
  ]);
  $registrant_type
    ->save();

  // Re-calculate dependencies by re-saving fields.
  $config_names = $config_factory
    ->listAll('field.field.registrant.registrant.');
  foreach ($config_names as $name) {

    // Remove prefix
    $id = str_replace('field.field.', '', $name);
    $entity = \Drupal\field\Entity\FieldConfig::load($id);
    $entity
      ->save();
  }
}