Magento 2 – Save Custom Customer Attribute Value Programmatically

customercustomer-attributemagento2

How can I save a custom Customer Attribute value programmatically?
I have tried below code but it didn't work.

protected $customer;

public function __construct(
    \Magento\Customer\Model\Customer $customer
)
{
    $this->customer = $customer;
}

...
...

$customerId = "1";
$customer = $this->customer->load($customerId);
$data = "customer attribute value";
$customerData = $customer->getDataModel();
$customerData->setCustomAttribute('customer_attribute_code',$data);
$customer->updateData($customerData);
$customer->save();

Is there any other method to save the customer attribute?

Best Answer

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');
Related Topic