How to save customer attribute value in custom script in Magento 2.
The prerequisite is to add first your new attribute programatically.
To do add a customer attribute please review these:
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityHow to save customer attribute value in custom script in Magento 2.
The prerequisite is to add first your new attribute programatically.
To do add a customer attribute please review these:
This is how it can be done with customer save method:
/** @var \Magento\Customer\Model\CustomerFactory $customerFactory */
/** @var \Magento\Customer\Model\Customer $customer */
/** @var \Magento\Customer\Model\Data\Customer $customerData */
$customer = $customerFactory->create()
$customerData = $customer->getDataModel();
$customerData->setCustomAttribute('my_attr_code', $val);
$customer->updateData($customerData);
$customer->save();
And this is how it can be done updating only one attribute value:
/** @var \Magento\Customer\Model\CustomerFactory $customerFactory */
/** @var \Magento\Customer\Model\Customer $customer */
$customer = $customerFactory->create();
//$customer->setId($customerId); // This seem redundant
/** @var \Magento\Customer\Model\Data\Customer $customerData */
// interface \Magento\Customer\Api\Data\CustomerInterface
$customerData = $customer->getDataModel();
$customerData->setId($customerId);
$customerData->setCustomAttribute('my_custom_attribute', $value);
$customer->updateData($customerData);
/** @var \Magento\Customer\Model\ResourceModel\Customer $customerResource */
/** @var \Magento\Customer\Model\ResourceModel\CustomerFactory $customerResourceFactory */
$customerResource = $customerResourceFactory->create();
if ($value != "") {
$customerResource->saveAttribute($customer, 'my_custom_attribute');
}
I have a quite nice solution for this :
protected $customerRepository;
public function __construct(
\Magento\Customer\Api\CustomerRepositoryInterface $customerRepository
) {
$this->customerRepository = $customerRepository;
}
...
public function updateCustomerAttribute($customerId, $attributeCode, $value) {
$customerData = $this->customerRepository->getById($customerId);
$customerData->setCustomAttribute($attributeCode, $value);
$this->customerRepository->save($customerData);
}