Magento – Save customer custom address attribute programmatically

addressaddress-attributecustom-attributescustomer-addressmagento2

I have created new address attribute hide_address with yes no value. Using setup script:

    if(version_compare($context->getVersion(), '1.0.2', '<')) {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $customerSetup = $objectManager->create('Vendor\Module\Setup\CustomerSetup2');
        $customerSetup->installAttributes($customerSetup);
    }

In CustomerSetup2.php I have used this code:

public function installCustomerAddressAttributes($customerSetup)
{
    $customerSetup->addAttribute('customer_address',
        'hide_address',
        [
            'label' => 'Hide Address',
            'system' => 0,
            'user_defined' => true,
            'position' => 100,
            'sort_order' => 100,
            'visible' => true,
            'default_value' => '',
            'note' => '',
            'type' => 'int',
            'input' => 'boolean',
            'source' => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean',

        ]
    );

    $customerSetup->getEavConfig()->getAttribute('customer_address', 'hide_address')->setData('is_user_defined', 1)->setData('default_value', '')->setData('used_in_forms', ['adminhtml_customer_address', 'customer_register_address', 'customer_address_edit'])->save();
}

Now I need to save it in a controller programmatically. I have used this code to save address:

$address = $this->addressDataFactory->create();
$address->setFirstname('Shoaib')
    ->setLastname('Munir')
    ->setCountryId('pk')
    ->setCity('ABC')
    ->setPostcode('12345')
    ->setCustomerId(2)
    ->setStreet(array('Line 1','Line 2'))
    ->setTelephone('1234567')
    ->setFax('12345')
    ->setVatId('12345')
    ->setIsDefaultBilling('1')
    ->setIsDefaultShipping('1')
    ->setHideAddress(1)
;

It is giving me this error:

Call to undefined method
Magento\Customer\Model\Data\Address::setHideAddress()

Then I have tried this:

$address->setCustomAttribute('hide_address', 1); 

Using above code it is giving me this error:

Exception #0 (Magento\Framework\Validator\Exception): "Hide Address"
is a required value.

I have also tried this:

$address->setData('hide_address',1);

Using above code it is giving me this error:

Exception #0 (Magento\Framework\Validator\Exception): "Hide Address"
is a required value.

Please help me find the solution. I am unable to find any.
This is also not working for me:
Save or Update custom customer address attribute data

Best Answer

As you have using Api interface, So, you have to add hide_address as an extension attribute of Magento\Customer\Api\Data\AddressInterface.

Create a <Module>/etc/extension_attributes.xml file to define a hide_address extension attribute.

<?xml version="1.0"?>
<!-- 
/**
 *
 * @author Amit Bera
 * @copyright Copyright (c) 2018-2020 amitbera.com
 */
 -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Api/etc/extension_attributes.xsd">
    <extension_attributes for="Magento\Customer\Api\Data\AddressInterface">
        <attribute code="hide_address" type="int"/>
    </extension_attributes>
</config>

Save using below code:

$address->setFirstname('Shoaib')
    ->setLastname('Munir')
    ->setCountryId('pk')
    ->setCity('ABC')
    ->setPostcode('12345')
    ->setCustomerId(2)
    ->setStreet(array('Line 1','Line 2'))
    ->setTelephone('1234567')
    ->setFax('12345')
    ->setVatId('12345')
    ->setIsDefaultBilling('1')
    ->setIsDefaultShipping('1');

$addressExtension = $address->getExtensionAttributes();
if(null === $addressExtension){
  // $addressExtensionFactory is instance of \Magento\Customer\Api\Data\AddressExtensionFactory
 $addressExtension =$addressExtensionFactory->create(); 
}

$addressExtension->setHideAddress(1)
$address->setExtensionAttributes($addressExtension);

I am not sure why this is saving. Please assign attribute set to this attribute and see what happen:

/** @var \Magento\Eav\Setup\EavSetup $eavSetup */
$eavSetup->addAttributeToSet(
            \Magento\Customer\Api\AddressMetadataInterface::ENTITY_TYPE_ADDRESS,
            \Magento\Customer\Api\AddressMetadataInterface::ATTRIBUTE_SET_ID_CUSTOMER,
            null,'hide_address');

Source: Magento2 : user define customer attribute not save value while create / save from admin

Related Topic