Magento – Set custom address attribute value programmatically

custom-attributescustomer-addresseav-attributesmagento2

I'm using Magento v2.1.6 and I have created a 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 save/update in one of the customer address like this:

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

public function execute(){
 $addressId = 1;
 $subdistrict = "Harbor City";
 $address = $this->addressRepository->getById($addressId);
 $address->setCustomAttribute('subdistrict',$subdistrict); 
 $this->addressRepository->save($address);
}

But I am always getting an error saying :

{"0":"Class object does not exist","1":"#0
/var/www/Project/lib/internal/Magento/Framework/Reflection/MethodsMap.php(155):
ReflectionClass->__construct('object')\n#1
/var/www/Project/lib/internal/Magento/Framework/Reflection/MethodsMap.php(106)

Best Answer

For show it on address/edit.phtml like :

<?=$block->getAddress()->getShippingInfo();?>

Add in your di.xml

<preference for="Magento\Customer\Model\Data\Address" type="vendor\CustomerAccount\Model\Data\Address" />

And in your model :

<?php


namespace vendor\CustomerAccount\Model\Data;

class Address extends \Magento\Customer\Model\Data\Address
{
    /**
     * Get shipping_info
     *
     * @return string|null
     */
    public function getShippingInfo()
    {
        return $this->_get('shipping_info');
    }
}

The save is automatic if you have created it normaly