Set value of Customer Custom attribute in Magento 2
Magento 2 allows store owners and developers to extend customer information using a custom attribute in Magento.
Customer custom attributes are widely used to store additional data such as preferences, loyalty details, verification status, or any business-specific information that is not available by default.
In this blog, we will explain how to set or update the value of a customer custom attribute in Magento 2 programmatically.
Why Use Customer Custom Attribute in Magento?
Using a custom attribute in Magento helps you:
- Store additional customer-specific data
- Manage dynamic values after customer login
- Integrate external systems with Magento customer data
- Automate updates based on customer actions
- Improve personalization and user experience
Magento 2 offers APIs to securely manage customer data using the repository pattern, ensuring scalability and future compatibility.
To know how to create custom attributes for a customer, you can check the following:
1. Using Installer/Patch, click here
2. Without using Installer/Patch, click here
We will use a Controller file to set the value of custom attributes.
<?php
namespace Webkul\CustomerAttribute\Controller\Account;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Data\Form\FormKey\Validator as FormKeyValidator;
use Magento\Framework\View\Result\PageFactory;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Api\Data\CustomerInterfaceFactory;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Api\DataObjectHelper;
class SavePrice extends \Magento\Customer\Controller\AbstractAccount
{
/**
* @var \Magento\Customer\Model\Session
*/
protected $_customerSession;
/**
* @var \Magento\Framework\Data\Form\FormKey\Validator
*/
protected $_formKeyValidator;
/** @var CustomerRepositoryInterface */
protected $_customerRepository;
/**
* @var \Magento\Customer\Model\Customer\Mapper
*/
protected $_customerMapper;
/**
* @var CustomerInterfaceFactory
*/
protected $_customerDataFactory;
/**
* @var DataObjectHelper
*/
protected $_dataObjectHelper;
/**
* @param Context $context
* @param Session $customerSession
* @param FormKeyValidator $formKeyValidator
* @param CustomerRepositoryInterface $customerRepository
* @param CustomerInterfaceFactory $customerDataFactory
* @param DataObjectHelper $dataObjectHelper
* @param \Magento\Customer\Model\Customer\Mapper $customerMapper
* @param PageFactory $resultPageFactory
*/
public function __construct(
Context $context,
\Magento\Customer\Model\Session $customerSession,
FormKeyValidator $formKeyValidator,
CustomerRepositoryInterface $customerRepository,
CustomerInterfaceFactory $customerDataFactory,
DataObjectHelper $dataObjectHelper,
\Magento\Customer\Model\Customer\Mapper $customerMapper,
PageFactory $resultPageFactory
) {
$this->_customerSession = $customerSession;
$this->_customerRepository = $customerRepository;
$this->_customerMapper = $customerMapper;
$this->_customerDataFactory = $customerDataFactory;
$this->_dataObjectHelper = $dataObjectHelper;
$this->_formKeyValidator = $formKeyValidator;
parent::__construct(
$context
);
}
/**
* Retrieve customer session object
*
* @return \Magento\Customer\Model\Session
*/
protected function _getSession()
{
return $this->_customerSession;
}
/**
* Check customer authentication
*
* @param RequestInterface $request
* @return \Magento\Framework\App\ResponseInterface
*/
public function dispatch(RequestInterface $request)
{
$loginUrl = $this->_objectManager->get('Magento\Customer\Model\Url')->getLoginUrl();
if (!$this->_customerSession->authenticate($loginUrl)) {
$this->_actionFlag->set('', self::FLAG_NO_DISPATCH, true);
}
return parent::dispatch($request);
}
/**
* Default customer account page
*
* @return \Magento\Framework\View\Result\Page
*/
public function execute()
{
/** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
if ($this->getRequest()->isPost()) {
if (!$this->_formKeyValidator->validate($this->getRequest())) {
return $this->resultRedirectFactory->create()->setPath(
'*/*/index',
['_secure' => $this->getRequest()->isSecure()]
);
}
$customerData = $this->getRequest()->getParams(); //get attributes value from form
$customerId = $this->_getSession()->getCustomerId();
// get customer saved data
$savedCustomerData = $this->_customerRepository->getById($customerId);
$customer = $this->_customerDataFactory->create();
//merge saved customer data with new values
$customerData = array_merge(
$this->_customerMapper->toFlatArray($savedCustomerData),
$customerData
);
$customerData['id'] = $customerId;
$this->_dataObjectHelper->populateWithArray(
$customer,
$customerData,
'\Magento\Customer\Api\Data\CustomerInterface'
);
//save customer
$this->_customerRepository->save($customer);
$this->messageManager->addSuccess(__('Value has been successfully saved'));
return $this->resultRedirectFactory->create()->setPath(
'*/*/index',
['_secure' => $this->getRequest()->isSecure()]
);
}
}
}
By using the same approach, you can set the value for the customer’s custom attribute.
Best Practices to Follow:
- Always use CustomerRepositoryInterface
- Never save customer models directly
- Validate customer login before updating data
- Handle exceptions properly
- Keep attribute codes consistent and meaningful
- Use clean and maintainable controller logic
Setting the value of a custom attribute in Magento is an essential feature for advanced customer data management.
By using a custom controller and Magento’s repository pattern, you can safely update customer attributes while maintaining performance and scalability.
This approach enables you to extend Magento’s customer functionality without modifying core files, keeping your implementation aligned with Magento development standards.
For technical assistance, please get in touch with us via email at support@webkul.com.
Discover powerful solutions to enhance your Magento 2 store by exploring our Magento 2 plugins page.
Bring your vision to life with custom-built solutions—hire skilled Magento 2 developers today.
Happy Coding!!