Magento – Save or Update custom customer address attribute data

custom-attributescustomer-addressmagento2

I created custom attribute for customer address like this:

$customerEntity = $customerSetup->getEavConfig()->getEntityType('customer_address');
            $attributeSetId = $customerEntity->getDefaultAttributeSetId();

            $attributeSet = $this->attributeSetFactory->create();
            $attributeGroupId = $attributeSet->getDefaultGroupId($attributeSetId);

            $customerSetup->addAttribute('customer_address', 'subdistrict', [
                'type' => 'varchar',
                'label' => 'District',
                'input' => 'text',
                'required' => false,
                'visible' => true,
                'visible_on_front' => true,
                'user_defined' => false,
                'sort_order' => 83,
                'position' => 83,
                'system' => 0,
            ]);

            $attribute = $customerSetup->getEavConfig()->getAttribute('customer_address', 'subdistrict')
                ->addData([
                    'attribute_set_id' => $attributeSetId,
                    'attribute_group_id' => $attributeGroupId,
                    'used_in_forms' => ['adminhtml_customer_address', 'customer_address_edit', 'customer_register_address','customer_address']
                ]);
            $attribute->save();

i tried to add/update the data using customer address repository interface like this:

public function __construct( 
  \Magento\Customer\Api\AddressRepositoryInterface $addressRepository
    )
  { 
      $this->addressRepository = $addressRepository;
  }

$address = $this->addressRepository->getById('1');
          if(!empty($address->getId())){
            $subdistrict = '223';
            $address->setData('subdistrict',$subdistrict);
            $this->addressRepository->save($address);
          }

the problem is , it wont save the customer custom attribute data

Best Answer

Try below code:

$address = $this->addressRepository->getById(1);
if($address && $address->getId()) {
    $subdistrict = '223';        
    $address->setCustomAttribute('subdistrict', $subdistrict); 
    $this->addressRepository->save($address);
}
Related Topic