Question

I am using following extension: https://github.com/diglin/Diglin_Username2

The custom attribute 'username' is created and working fine during login.

But I need to update this attribute value along with other customer data programaticaly. But when I save customer, this attribute is emptied. Please suggest some solution.

Here is the code:

$customer = $objectManager->get('Magento\Customer\Model\Customer')->setWebsiteId($websiteId)->loadByEmail($email);
if(!$customer->getId()){
$customerFactory = $objectManager->create('Magento\Customer\Model\CustomerFactory');
$customer = $customerFactory->create();
$customerModelData = $customer->getDataModel();
$customerModelData->setCustomAttribute('username',$customerData['web_username']);
$customer->updateData($customerModelData);
$customerResource->saveAttribute($customer, 'username');
}

$customer->setStoreId($storeId);
$customer->setWebsiteId($websiteId);
$customer->setEmail($email);
$customer->setFirstname($customerData['first_name']);
$customer->setLastname($customerData['last_name']);
$customer->setGender($gender);
$customer->setGroupId($groupId);
$customer->setPassword($this->magentoPassword);
$customer->save();

Thanks in advance!

No correct solution

OTHER TIPS

The issue is fixed after I separate the logic of add and update. Add logic is working using customerFactory while update logic is working using customerRepository. Following code worked for me:

$customer = $objectManager->get('Magento\Customer\Model\Customer')->setWebsiteId($websiteId)->loadByEmail($email);
$newCustomer = true;
if(!$customer->getId()){
    $customerFactory = $objectManager->create('Magento\Customer\Model\CustomerFactory');
    $customer = $customerFactory->create();
    $customerModelData = $customer->getDataModel();
    $customerModelData->setCustomAttribute('username',$customerData['web_username']);
    $customer->updateData($customerModelData);
}else{
    $newCustomer = false;
    $customer = $this->customerRepository->getById($customer->getId());
  /*\Magento\Customer\Api\CustomerRepositoryInterface */
    $customer->setCustomAttribute('username', $customerData['web_username']);
}

$customer->setStoreId($storeId);
$customer->setWebsiteId($websiteId);
$customer->setFirstname($customerData['first_name']);
$customer->setLastname($customerData['last_name']);
$customer->setGender($gender);
$customer->setGroupId($groupId);

if(!$newCustomer){//old customer
    $this->customerRepository->save($customer, $this->magentoPassword);
}else{//new customer
    $customer->setPassword($this->magentoPassword);
    $customer->save();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top