0

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');
}
}

1 Answer 1

0

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.

1
  • Uncaught Error: Call to undefined method Magento\Customer\Model\ResourceModel\Customer\Interceptor::getCollection() in D:\Projects\xampp\htdocs\magento2\app\code\Tatva\Loginpopup\Controller\Index\save.php:33
    – Hiren
    May 24, 2018 at 12:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.