Magento 2: Save custom customer attribute value programmatically
I have got the solution
protected $customer;
protected $customerFactory;
public function __construct(
\Magento\Customer\Model\Customer $customer,
\Magento\Customer\Model\ResourceModel\CustomerFactory $customerFactory
)
{
$this->customer = $customer;
$this->customerFactory = $customerFactory;
}
...
...
$customerId = "1";
$customer = $this->customer->load($customerId);
$data = "customer attribute value";
$customerData = $customer->getDataModel();
$customerData->setCustomAttribute('customer_attribute_code',$data);
$customer->updateData($customerData);
$customerResource = $this->customerFactory->create();
$customerResource->saveAttribute($customer, 'customer_attribute_code');
You need to do it the strange Magento 2 way:-
public function __construct( \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository, ) { $this->_customerRepository = $customerRepository; } public function execute() { $customer = $this->_customerRepository->getById($customerId); $customer->setDob($data['dob']) ->setCustomAttribute('medicare_number',$data['medicare_number']) ->setCustomAttribute('medicare_reference',$data['medicare_reference']) ->setCustomAttribute('medicare_exp',$data['medicare_exp']); $this->_customerRepository->save($customer); }