Magento 2.x – how to set and get with a custom customer attribute programmatically
If you added an EAV attribute for your customer, and you now need to set it in a piece of code, the following snippet will be helpfull for you.
Constructor:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
protected $_customerSession; protected $_customer; protected $_customerFactory; public function __construct( Context $context, \Magento\Customer\Model\Customer $customer, \Magento\Customer\Model\ResourceModel\CustomerFactory $customerFactory, ) { $this->_customer = $customer; $this->_customerFactory = $customerFactory; parent::__construct($context); } |
Code:
1 2 3 4 5 6 7 8 |
$customer = $this->_customer->load($customerId); $customerData = $customer->getDataModel(); $customerData->setCustomAttribute('my-custom-field','This is the value'); $customer->updateData($customerData); $customerResource = $this->_customerFactory->create(); $customerResource->saveAttribute($customer, 'my-custom-field'); |
Happy coding.!