Question:

Magento 2 : optimize customer attributes save code

Brielle: 18 January 2022

i am trying to save data using customer attributes and the below code work fine, can i further optimize below code

Thankyou

<?php
namespace Tatva\Loginpopup\Controller\Index;

use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Filesystem\DirectoryList;

class save extends \Magento\Framework\App\Action\Action
{


protected $_resultPageFactory;
protected $customerFactory;
protected $customer;

public function __construct(
    Context $context, 
    \Magento\Customer\Model\Customer $customer,
    \Magento\Customer\Model\ResourceModel\CustomerFactory $customerFactory,
    \Magento\Framework\View\Result\PageFactory $resultPageFactory)
{
    $this->customer = $customer;
    $this->customerFactory = $customerFactory;
    $this->resultPageFactory = $resultPageFactory;
    parent::__construct($context);

}

public function execute()
{
    $params = $this->getRequest()->getParams();
    $customerId = $params['customer_id'];
    $industry = $params['industry'];
    $job_profile = $params['job_profile'];

    $customer = $this->customer->load($customerId);
    $customerData = $customer->getDataModel();
    $customerData->setCustomAttribute('industry_attribute',$industry);
    $customerData->setCustomAttribute('jobProfile_attribute',$job_profile);
    $customer->updateData($customerData);

    $customerResource = $this->customerFactory->create();
    $customerResource->saveAttribute($customer, 'industry_attribute');
    $customerResource->saveAttribute($customer, 'jobProfile_attribute');
}
}

Answer:
Cameron: 18 January 2022

Try below code, that will work faster than your code.

$customerModel = $this->customerFactory->create()->getCollection()
                    ->addFieldToFilter('entity_id', $customerId)->getLastItem();

$customerModel->setIndustryAttribute($industry);
$customerModel->setJobprofileAttribute($job_profile);
$customerModel->save();

Hope this will help you.