Tuesday, April 26, 2022

redirect custom path with params magento

 Code

<?php
namespace Icube\Customer\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Exception\AlreadyExistsException;
use Magento\Framework\Exception\LocalizedException;

class ValidateTelephone implements ObserverInterface
{
    protected $_request;
    protected $_customerManagement;
    protected $_messageManager;
    protected $_responseFactory;
    protected $_url;
    protected $_resulFactory;

    public function __construct(
        \Magento\Framework\App\RequestInterface $request,
        \Icube\Customer\Model\CustomerManagement $customerManagement,
        \Magento\Framework\Message\ManagerInterface $messageManager,
        \Magento\Framework\App\ResponseFactory $responseFactory,
        \Magento\Framework\UrlInterface $url,
        \Magento\Framework\Controller\ResultFactory $resulFactory
    ) {
        $this->_request = $request;
        $this->_customerManagement = $customerManagement;
        $this->_messageManager = $messageManager;
        $this->_responseFactory = $responseFactory;
        $this->_url = $url;
        $this->_resultFactory = $resulFactory;
    }

    /**
     *
     * @param \Magento\Framework\Event\Observer $observer
     * @return void
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $phone = $this->_request->getParam('telephone');
        if ($this->_customerManagement->isTelephoneAvailable($phone) === false) {
            $this->_messageManager->addError("Your phone number is already registered, please change your phone number.");
            $customerUrl = $this->_url->getUrl('customer/account/create');
            $resultRedirect = $this->_resultFactory->create(\Magento\Framework\Controller\ResultFactory::TYPE_REDIRECT);
            $resultRedirect->setPath($customerUrl, ['params' => $this->_request->getParams()]);
            // or
            //throw new LocalizedException(
            //    __("Your phone number is already registered, please change your phone number.")
            //);
        }
        //  $tmp = "hi" ;
        //  die(json_encode(is_object($tmp) ? get_class_methods($tmp) : $tmp));

    }

}

References

0 comments:

Post a Comment