You are here

function address_update_8100 in Address 8

Remove the stored address formats, update field settings.

File

./address.install, line 34
Requirements and update functions for the address module.

Code

function address_update_8100() {

  // Clear the caches to ensure the entity type is gone.
  \Drupal::entityTypeManager()
    ->clearCachedDefinitions();
  \Drupal::service('entity_type.repository')
    ->clearCachedDefinitions();

  // Remove the underlying config.
  $config_factory = \Drupal::configFactory();
  $names = $config_factory
    ->listAll('address.address_format.');
  foreach ($names as $name) {
    $config_factory
      ->getEditable($name)
      ->delete();
  }

  // Update the 'fields' setting of each address field.
  // Replace 'recipient' with the new name fields.
  $entity_field_manager = \Drupal::service('entity_field.manager');
  $entity_field_map = $entity_field_manager
    ->getFieldMapByFieldType('address');
  foreach ($entity_field_map as $entity_type_id => $fields) {
    foreach ($fields as $field_name => $field_info) {
      foreach ($field_info['bundles'] as $bundle) {
        $field = FieldConfig::loadByName($entity_type_id, $bundle, $field_name);
        if (!$field) {

          // This is a base field, nothing can be done.
          continue 2;
        }
        $used_fields = $field
          ->getSetting('fields');
        if (!empty($used_fields['recipient'])) {
          $used_fields['givenName'] = 'givenName';
          $used_fields['additionalName'] = 'additionalName';
          $used_fields['familyName'] = 'familyName';
        }
        else {

          // The recipient field wasn't enabled previously.
          $used_fields['givenName'] = '';
          $used_fields['additionalName'] = '';
          $used_fields['familyName'] = '';
        }
        unset($used_fields['recipient']);
        $field
          ->setSetting('fields', $used_fields);
        $field
          ->save();
      }
    }
  }
}