Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set custom Customer attribute value programmatically Magento 2

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.

like image 840
Mr. Metz Avatar asked Sep 28 '16 06:09

Mr. Metz


1 Answers

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
}
like image 194
George Duta Avatar answered Sep 27 '22 23:09

George Duta