I’ve created a new custom attribute as below:
namespace VendorModuleSetup;
use MagentoEavSetupEavSetup;
use MagentoEavSetupEavSetupFactory;
use MagentoFrameworkSetupInstallDataInterface;
use MagentoFrameworkSetupModuleContextInterface;
use MagentoFrameworkSetupModuleDataSetupInterface;
use MagentoCustomerModelCustomer;
use MagentoEavModelConfig;
class InstallData implements InstallDataInterface
{
private $eavSetupFactory;
private $eavConfig;
public function __construct(EavSetupFactory $eavSetupFactory, Config $eavConfig)
{
$this->eavSetupFactory = $eavSetupFactory;
$this->eavConfig = $eavConfig;
}
public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
$attributes = [
'id_number' => [
'type' => 'varchar',
'label' => 'ID Number',
'input' => 'text',
'required' => false,
'user_defined' => true,
'visible' => true,
'position' => 120,
'system' => false,
],
];
foreach ($attributes as $attributeCode => $attributeDetails) {
$eavSetup->addAttribute(Customer::ENTITY, $attributeCode, $attributeDetails);
$attribute = $this->eavConfig->getAttribute(Customer::ENTITY, $attributeCode);
$attribute->setData(
'used_in_forms',
['adminhtml_customer', 'customer_account_create', 'customer_account_edit']
);
$attribute->save();
}
}
}
I’ve tried several solutions to save any data in this field using order success observer, but in vain. No errors and customer save works successfully. e.g.:
if ($isCustomerLoggedIn) {
//$customer = $this->customerRepository->getById($customerId);
$customer = $this->customerFactory->create()->load($customerId);
// Set custom attributes
$customerData->setCustomAttribute('id_number', $this->customerSession->getData('id_number'));
$customer->setDob($this->customerSession->getData('dob'));
// Save custom data in customer entity
$customerDataModel = $customer->getDataModel();
$customerDataModel->setCustomAttribute('id_number', '12345');
try {
$customer->updateData($customerDataModel);
//$this->customerRepository->save($customer);
$customer->save();
$this->messageManager->addSuccessMessage(__('Customer data has been saved.'));
} catch (Exception $e) {
$this->messageManager->addErrorMessage(__('Error saving customer data %1', $e->getMessage()));
}
Any help? Please provide a working code for Magento 2.4 so I can try it again. Note that even setDob seems not working as well.
Thanks in advance!