Multiselect attribute not saving in Magento 2.3.0
-
16-02-2021 - |
Question
I have created the multi-select attribute for customer address using below code.
Setup/UpgradeData.php
$customerEntity = $customerSetup->getEavConfig()->getEntityType('customer_address');
$attributeSetId = $customerEntity->getDefaultAttributeSetId();
$customerSetup->addAttribute('customer_address', 'address_purpose', [
'type' => 'text',
'label' => 'Address Purpose',
'input' => 'multiselect',
'required' => false,
'visible' => false,
'user_defined' => true,
'sort_order' => 1000,
'position' => 1000,
'system' => 0,
'backend' => 'Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend',
'source' => 'Vendor\Module\Model\Entity\Attribute\Source\AddressPurpose'
]);
$attribute = $customerSetup->getEavConfig()->getAttribute('customer_address', 'address_purpose')
->setData([
'used_in_forms' => ['adminhtml_customer_address', 'customer_address_edit', 'customer_register_address','customer_address']
]);
$attribute->save();
Here is my AddressPurpose.php
use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource;
class AddressPurpose extends AbstractSource
{
public function getAllOptions()
{
return [
'option1' => [
'label' => 'Delivery',
'value' => 'delivery'
],
'option2' => [
'label' => 'General',
'value' => 'general'
]
];
}
}
Using above code customer address attribute created successfully.
When I open any customer in admin and selected the option and click Save, The customer getting saved but the selected options are not getting saved.
Again I edit the same customer, Address purpose attribute values empty with none selected.
Have anyone face this issue? Please help me on this. Thanks
Solution
When creating the customer attribute, please take care about following things:
Attribute is added to the attribute set, group
customer_eav_attribute
eav_entity_attribute
Attribute is assigned to customer forms
customer_form_attribute
And the last one the most important as somehow, people just skip over it and wondering why the customer attribute does not want to save from the backend: Please make sure to set "is_system" flag in "customer_eav_attribute" table to 0, otherwise the attribute will not be saved.
It can be done by setting the attribute option to "system" => 0 in attribute parameters inside the install/upgrade script.
Don't forget to flush your cache after all!