Set custom Customer attribute value programmatically Magento 2

Mr. Metz picture Mr. Metz · Sep 28, 2016 · Viewed 6.9k times · Source

I am importing some customers with :

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

        $customerFactory = $objectManager->create('\Magento\Customer\Model\CustomerFactory');


        $customer = $objectManager->create('Magento\Customer\Model\Customer')->setWebsiteId(1)->loadByEmail('[email protected]');


        try {
            if(!empty($customer->getData('email')))
            {
                $customer->setAttr1(1); // Attr1 = Name of the custom Attribute 
                $customer->setAttr2(2); // Attr2 = Name of the custom Attribute 
            }
            else
            {
                $customer = $customerFactory->create()->setWebsiteId(1);
            }


            $customer->setLastname("Lastname");

            $customer->setFirstname("Firsty");

            .....

            $customer->save();

The customer is saved with all his standard attributes correctly but my new attributes won't be saved anyway. I've also tried :

$customer->setCustomAttribute('Attr1','value');

but this didn't work too.

The custom Attribute are shown correclty in Magentos 2 backoffice and the values are saved correctly too if creating a customer manually.

Answer

George Duta picture George Duta · Oct 2, 2017

Have you tried:

$customer-> setData('Attr1','value');

and don't forget to save and log the information:

try {
    $customer->save();
} catch (\Exception $e) {
    // log exception so you can debug the issue if there is one
}