Magento 2: Fix Magic Getters for Custom Attribute Not Working

customermagento2

I have added custom attribute to customer, "authnet_account_number".

It is running, also getting shown on the customer create form in Adminhtml.

But the magic getter for the attribute,$customer->getAuthnetAccountNumber() is not working.

Here is the upgrade schema for the attribute,

 public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        /** @var \Magento\Customer\Setup\CustomerSetup $customerSetup */
        $customerSetup = $this->customerSetupFactory->create(['setup' => $setup]);

        $setup->startSetup();

        /**
         * authnetcim_profile_id customer attribute: Stores CIM profile ID for each customer.
         */
        if ($customerSetup->getAttributeId('customer', 'authnet_account_number') === false) {
            $customerSetup->addAttribute(
                Customer::ENTITY,
                'authnet_account_number',
                [
                    'label'            => 'Authnet account number to be used',
                    'type'             => 'varchar',
                    'input'            => 'text',
                    'default'          => '',
                    'position'         => 70,
                    'visible'          => true,
                    'required'         => false,
                    'system'           => false,
                    'user_defined'     => true,
                    'visible_on_front' => false,
                ]
            );

            $profileIdAttr = $customerSetup->getEavConfig()->getAttribute(
                Customer::ENTITY,
                'authnet_account_number'
            );

            $profileIdAttr->addData([
                'attribute_set_id' => $customerSetup->getDefaultAttributeSetId(Customer::ENTITY),
                'attribute_group_id' => $customerSetup->getDefaultAttributeGroupId(Customer::ENTITY),
                'used_in_forms' => [],
            ]);

            $this->attributeRepository->save($profileIdAttr);
        } 
        $setup->endSetup();
    }

Best Answer

You need to use repository for this as follows.

$customerRepository = $objectManager->get('Magento\Customer\Api\CustomerRepositoryInterface');
$customer = $customerRepository->getById(1);
$cattrValue = $customer->getCustomAttribute('my_custom_attribute');

To set...

$customer = $customerFactory->create();
$customerData = $customer->getDataModel();
$customerData->setCustomAttribute('my_attr_code', $val);
$customer->updateData($customerData);
$customer->save();
Related Topic