0

This question already has an answer here:

I need to redirect customers back to the previous page when a customers get registered or log in to the account like when a customers need to add a review and need to log in to their account before making any comments. So currently Magento 2.1.6 redirects to customer account page when a customers want to review the product.

Does anyone has a solution?

marked as duplicate by Siarhey Uchukhlebau, liyakat, Moose, Keyul Shah, benmarks Jun 17 '17 at 15:33

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

0

You can follow the following approach:

=>Save the referrer url in session when customer is redirected to login page. You can get the referrer url and set that url by the help of below code:

$referrerurl = $this->_redirect->getRefererUrl();
$this->getCustomerSession()->setLoginReferUrl($referrerurl);

=> Then after login you can use that url to redirect previous page as shown below:

$preurl=$this->getCustomerSession()->getLoginReferUrl();  
$resultRedirect=$this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
$resultRedirect->setUrl($resultRedirect);
return $resultRedirect;
0

To redirect to the previous url after customer login Magento uses refer parameter in login url. If you want to get Login url with refer param in your custom template the add this code in your block file

protected $urlEncoder;

In __contruct function initialise urlEncoder class

public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    \Magento\Framework\Url\EncoderInterface $urlEncoder,
    array $data = []
) {
    $this->urlEncoder = $urlEncoder;
    parent::__construct($context, $data);
}

and then create and set login url like this -

protected function _construct()
{
    parent::_construct();
    $queryParam = $this->urlEncoder->encode(
            $this->getUrl('*/*/*', ['_current' => true])
        );
        $this->setLoginLink(
            $this->getUrl(
                'customer/account/login/',
                [Url::REFERER_QUERY_PARAM_NAME => $queryParam]
            )
        );
}

In your template you can get Login Url with refer parameter by $block->getLoginLink();

Not the answer you're looking for? Browse other questions tagged or ask your own question.