Reading list Switch to dark mode

    Set value of Customer Custom attribute in Magento 2

    Updated 22 February 2024

    Here we will learn, How to set value of Customer Custom attribute in Magento 2.
    To know how to create custom attributes for customer, you can check 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 customer’s custom attribute.

    Searching for an experienced
    Magento 2 Company ?
    Find out More
    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home