Quantcast
Channel: Webkul Blog
Viewing all articles
Browse latest Browse all 5490

How to set value of Customer Custom attribute in Magento 2.0.x

$
0
0

Here we will learn, How to set value of Customer Custom attribute in Magento 2.0.x

Using Controller file to set the value.

<?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 PageFactory $resultPageFactory
     * @SuppressWarnings(PHPMD.ExcessiveParameterList)
     */
    public function __construct(
        Context $context,
        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,
            $customerSession,
            $formKeyValidator,
            $resultPageFactory
        );
    }

    /**
     * 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('path', ['_secure'=>$this->getRequest()->isSecure()]);
        }            
    }
}

By using the same approach you can set the value for customer’s custom attribute.


Viewing all articles
Browse latest Browse all 5490

Trending Articles