Magento – Magento2 | How to save EAV attribute in Customer Address

customer-addresseavmagento2

I want to add 'district' field in customer address.

First, I added the EAV attribute in customer_address.

UpgradeData.php

public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
    $setup->startSetup();

    $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

    if (version_compare($context->getVersion(), '2.1.0', '<')) {

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

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

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

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

    $setup->endSetup();
}

And, I tried to add the address in checkout page. (mywebsite.com/checkout)

It works. But 'district' field isn't filled.

When I tried in address book page, It works correctly.

How can I solve the problem?

Best Answer

Edit: Magento2,those customer fields will be show at checkout which available at customer_address,customer_register_address Form

So,You need to available this field at checkout form by changing below code:

used_in_forms' => ['adminhtml_customer_address', 'customer_address_edit', 'customer_register_address']

to

used_in_forms' => ['adminhtml_customer_address', 'customer_address_edit', 'customer_register_address','customer_address']
Related Topic