I am trying to save data programmatically to an address field from the Address module.

I am not successful.

First, when I dsm() a node with the address field filled out, it looks like this:

        [field_addr] => Array
                [x-default] => Array
                        [0] => Array
                                [langcode] => 
                                [country_code] => US
                                [administrative_area] => CA
                                [locality] => San Diego
                                [dependent_locality] => 
                                [postal_code] => 91945
                                [sorting_code] => 
                                [address_line1] => 123 main st
                                [address_line2] => apt 2
                                [organization] => 
                                [given_name] => 
                                [additional_name] => 
                                [family_name] => 



However, no matter how I try to save it to my node, it doesn't work.

I create an array that looks like this:

    [x-default] => Array
            [0] => Array
                    [address_line1] => Australian Club
                    [address_line2] => Royal Lane
                    [locality] => Sydney
                    [administrative_area] => NSW
                    [country] => Australia



Let's say with the name, $address_save

And then do the following:

$node->set('field_addr', $address_save);

No luck. My node saves with other fields, but this one doesn't. I've also tried it without the x-default key around it as well as without a delta, but neither of those work either.

How can I save values to an Address field inside of a node?

1 Answer 1


The problem here was due to Drupal failing silently (or obfuscating the error - maybe because I was running this in cron) but it was due to the address not having all of the required fields set to the correct values for the country in question - mainly using the actual country name instead of the country code.

Once the country code was swapped in it worked. I switched the country around to the country code like this:

function MY_MODULE_get_country_code($country) {
  $countries = MY_MODULE_country_list();
  $flipped_countries = array_flip($countries);
  $country_code = $flipped_countries[$country];
  return $country_code;

function MY_MODULE_country_list() {
  $countries = \Drupal\Core\Locale\CountryManager::getStandardList();
  foreach ($countries as $key => $value) {
    $countries[$key] = $value->__toString();
  return $countries;

It worked correctly.

  • Would have been great if you posted your final solution. :(
    – liquidcms
    Apr 22, 2020 at 19:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.