You are here

function address_update_8104 in Address 8

Transfers the default country code widget setting to the field config.

File

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

Code

function address_update_8104() {
  $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;
        }
        $form_display = EntityFormDisplay::load("{$entity_type_id}.{$bundle}.default");
        $address_component = $form_display ? $form_display
          ->getComponent($field_name) : NULL;
        if (!$form_display || !$address_component) {

          // The bundle doesn't have a form display, or the field is hidden.
          continue;
        }
        if (empty($address_component['settings']['default_country'])) {

          // No default country has been specified.
          continue;
        }
        $default_country = $address_component['settings']['default_country'];
        if ($default_country == 'site_default') {
          $default_country = \Drupal::config('system.date')
            ->get('country.default');
        }

        // Remove the setting from the widget.
        $address_component['settings'] = [];
        $form_display
          ->setComponent($field_name, $address_component);
        $form_display
          ->save();

        // Set the default country on the field.
        if ($default_country) {
          $field
            ->setDefaultValue([
            [
              'country_code' => $default_country,
            ],
          ]);
          $field
            ->save();
        }
      }
    }
  }
}