Skip to content

Instantly share code, notes, and snippets.

@fredysan
Last active March 31, 2021 17:39
Show Gist options
  • Save fredysan/6990644dd3fdd8199311c2d8e69c7a92 to your computer and use it in GitHub Desktop.
Save fredysan/6990644dd3fdd8199311c2d8e69c7a92 to your computer and use it in GitHub Desktop.
How to get the full name of a State from an address field

Drupal 8 - Address field.

How to get the full Name of a State from an address Field

  $subdivisionRepo = \Drupal::service('address.subdivision_repository');
  $address = $node->get('field_address')->first()->toArray();
  $city = $address['locality'];
  // $subdivisionRepo->get() returns an object of type CommerceGuys\Addressing\Subdivision\Subdivision.
  $state = $subdivisionRepo->get($address['administrative_area'], [$address['country_code']])->getName();

How to look up for the State code of a State name.

  $state_name = 'New York';
  $country_code = 'US';
  $subdivisionRepo = \Drupal::service('address.subdivision_repository');
  $states = $subdivisionRepo->getAll($country_code);
  $state_code = array_search($state_name, $states);

How to update an Address field

  $address_line1 = 'Address line 1';
  $city = 'Wilmington';
  $state_code = 'DE';
  $postal_code = '19801';
  $address = $node->field_address->first();
  $address->set('address_line1', $address_line1;
  $address->set('locality', $city);
  $address->set('administrative_area', $state_code);
  $address->set('postal_code', $postal_code;
  $node->field_address->set(0, $address);

How to set values of an Address field on node creation

  $address_line1 = 'Address line 1';
  $address_line2 = 'Address line 2';
  $city = 'Wilmington';
  $state_code = 'DE';
  $postal_code = '19801';
  $new_node = \Drupal::service('entity_type.manager')->getStorage('node')->create([
    'field_address' => [
      'country_code' => 'US',
      'address_line1' => $address_line1,
      'address_line2' => $address_line2,
      'locality' => $city,
      'administrative_area' => $state_code,
      'postal_code' => $postal_code,
    ],
    'status' => 1,
  ]);
  $new_node->save();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment