How to set an address field with data from another address field?

Created on 16 April 2020, about 4 years ago
Updated 25 March 2024, 3 months ago

I am trying to figure out how to programmatically set an Address field on an entity with the value of a different Address field from a different entity.

This should be trivial and i have tried this:

function example_user_insert($user) {
  $profile = Profile::create([
    'type' => 'customer',
    'uid' => $user->id(),
    'is_default' => true,
  ]);

  $profile->set('address', $user->field_billing_address);
  $profile->save();
}

Although the profile entity gets saved; the Address field is not filled in and there are no errors generated. I have successfully set pieces of an Address field with its pieces (country, city, etc); but hoping i don't need to do this as it seems like i should be able to just do it as i show above. I have done a similar technique for entity ref fields where i simply do something like:

$node->set('term1', $node2->term2);

and it works as expected.

πŸ’¬ Support request
Status

Active

Version

1.0

Component

Code

Created by

πŸ‡¨πŸ‡¦Canada liquidcms

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • πŸ‡΅πŸ‡±Poland Bartosz Pijet
        use Drupal\profile\Entity\Profile;
    
        $profile = Profile::load(123123);
        $addresses = $profile->get('address');
        $addresses->setValue(array(
            'langcode' => 'pl',
            'country_code' => 'PL',
            'locality' => 'Gniezno',
            'postal_code' => '11-500',
            'address_line1' => 'Nieznana',
            'address_line2' => '17/28',
            'given_name' => 'Piotr',
            'family_name' => 'Kowalski',
        ));
        $profile->save();
        
        // Debug print so you can validate that it is working.
        ksm($profile->get('address'));
    
  • πŸ‡¨πŸ‡¦Canada liquidcms

    Not entirely sure I get what you are doing; but i think its exactly what I don't want to do.

    Should be something like this:

    $profile = Profile::load(123123);
    $address1 = $profile->get('address');
    $profile->set('field_address2', $address1);
    $profile->save();
    
  • πŸ‡¬πŸ‡§United Kingdom dahousecat

    This should do it:

    $profile = Profile::load(123123);
    $address1 = $profile->get('address');
    $profile->set('field_address2', $address1->first()->getValue());
    $profile->save();
    

    Of course if this is multi cardinality replace first() with a loop.

Production build 0.69.0 2024