Magento – Magento 2 custom address fields not saving to database from checkout

checkoutcustomer-addressmagento2

Through a setup script I created two new customer address fields for Magento 2. These field show up nicely in the backend and checkout. But, the values are not send from checkout to the api. Now the fields are not saved into the database.

Also, when editing the order address in the backend the values aren't stored. The values are only stored when editing the customer address through the customer itself.

What am I missing!? The Magento docs about adding a shipping field aren't helping me…

Best Answer

This usually happens when you specify "system" => "1" for the customer attributes. In order to make this working, you may create an upgrade script to set "system" => "0".

Here's an example:

app/code/YourVendor/YourModule/Setup/UpgradeData.php

use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Customer\Setup\CustomerSetupFactory
use Magento\Customer\Setup\CustomerSetup;
use Magento\Customer\Model\Customer;
...

public function __construct(
    CustomerSetupFactory $customerSetupFactory
) {
    $this->customerSetupFactory = $customerSetupFactory;
}
...

public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
    if (version_compare($context->getVersion(), '0.2.0') < 0) {
        $customerSetup = $this->customerSetupFactory->create();
        $customerSetup->getEavConfig()
            ->getAttribute(Customer::ENTITY, 'example_attribute_code')
            ->setData('is_user_defined', 1)
            ->setData('system', 1)
            ->save();
    }
}