2

In Magento 2, I have a custom login form in Header.

If a customer is on the product page for eg :

http://www.testwebsite.com/catalog/product/view/id/10

and login from header form then customer should redirect to the same product page instead of Customer Dashboard.

I have tried plugin code from this link.

Below is my custom header form code -

<?php 

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
$customerSession = $objectManager->get('Magento\Customer\Model\Session'); 

$urlInterface = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\UrlInterface');
$currenturl =  $urlInterface->getCurrentUrl();

if(!$customerSession->isLoggedIn()) {?>
<div class="header-login-main">
    <form action="<?php echo $this->getUrl('customer/account/loginPost');?>" method="post" id="login-form" novalidate="novalidate">
        <input name="form_key" value="" type="hidden">
        <div class="header-login" style="">
            <span>Email</span>
            <input name="login[username]" id="email" class="input-text" title="Email" data-validate="{required:true, 'validate-email':true}" aria-required="true" type="email">
        </div>
        <div class="header-login">
            <span>Password</span>
            <input name="login[password]" id="pass" class="input-text" title="Password" data-validate="{required:true}" aria-required="true" type="password">

        </div>
        <div class="header-login1">
            <button type="submit" class="action login primary" name="send" id="send2"><span>Login</span>
        </div>
    </form>
    <a href="<?php echo $this->getUrl('customer/account/forgotpassword');?>" class="f-right" style="padding: 3px 5px;">Reset Your Password?</a>
</div>

<?php } ?> 

Plugin Code -

<?php
namespace Vendor\Module\Plugin;
class LoginPostPlugin
{

    /**
     * Change redirect after login to home instead of dashboard.
     *
     * @param \Magento\Customer\Controller\Account\LoginPost $subject
     * @param \Magento\Framework\Controller\Result\Redirect $result
     */
    public function afterExecute(
        \Magento\Customer\Controller\Account\LoginPost $subject,
        $result)
    {
        $result->setPath('/'); // Change this to what you want
        return $result;
    }

}

I want to redirect the customer to $currenturl. Link tutorial can be able to redirect to the home page. Please suggest what needs to be done to achieve to redirect the customer to the current page.

Rahul
  • 763
  • 1
  • 12
  • 45

3 Answers3

2

Try the below:

Header Login Form :-

<?php 

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
$customerSession = $objectManager->get('Magento\Customer\Model\Session'); 

$urlInterface = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\UrlInterface');
$currenturl =  $urlInterface->getCurrentUrl();

if(!$customerSession->isLoggedIn()) {?>
<div class="header-login-main">
    <form action="<?php echo $this->getUrl('customer/account/loginPost');?>" method="post" id="login-form" novalidate="novalidate">
        <input name="form_key" value="" type="hidden">
        <input type="hidden" name='referer' value="<?php echo $currenturl ?>">
        <div class="header-login" style="">
            <span>Email</span>
            <input name="login[username]" id="email" class="input-text" title="Email" data-validate="{required:true, 'validate-email':true}" aria-required="true" type="email">
        </div>
        <div class="header-login">
            <span>Password</span>
            <input name="login[password]" id="pass" class="input-text" title="Password" data-validate="{required:true}" aria-required="true" type="password">

        </div>
        <div class="header-login1">
            <button type="submit" class="action login primary" name="send" id="send2"><span>Login</span>
        </div>
    </form>
    <a href="<?php echo $this->getUrl('customer/account/forgotpassword');?>" class="f-right" style="padding: 3px 5px;">Reset Your Password?</a>
</div>

<?php } ?> 

Plugin Code : -

<?php
namespace Vendor\Module\Plugin;
class LoginPostPlugin
{
    protected $request;
    public function __construct(
       \Magento\Framework\App\RequestInterface $request
    ) {
       $this->request = $request;
    }
    public function getPostReferer()
    {
        return $this->request->getPostValue('referer');
    }

    /**
     * Change redirect after login to home instead of dashboard.
     *
     * @param \Magento\Customer\Controller\Account\LoginPost $subject
     * @param \Magento\Framework\Controller\Result\Redirect $result
     */
    public function afterExecute(
        \Magento\Customer\Controller\Account\LoginPost $subject,
        $result)
    {
        $result->setPath($this->getPostReferer());
        return $result;
    }    
}
Rahul
  • 763
  • 1
  • 12
  • 45
Shivananda Chary
  • 565
  • 3
  • 10
1

Please try with the following code I have set the current url to the instant of $resultRedirect like this : $resultRedirect->setUrl($currenturl);

<?php

namespace Vendor\Module\Controller\Account;

use Magento\Customer\Model\Account\Redirect as AccountRedirect;
use Magento\Framework\App\Action\Context;
use Magento\Customer\Model\Session;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Customer\Model\Url as CustomerUrl;
use Magento\Framework\Exception\EmailNotConfirmedException;
use Magento\Framework\Exception\AuthenticationException;
use Magento\Framework\Data\Form\FormKey\Validator;
use Magento\Catalog\Api\ProductRepositoryInterface;

class LoginPost extends \Magento\Customer\Controller\Account\LoginPost {

    public function execute() {
        $urlInterface = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\UrlInterface');

        $sku = '24-MB01'; //Edit as per your product sku
        $_product = $this->productRepository->get($sku);
        $currenturl = $_product->getProductUrl();

        if ($this->session->isLoggedIn() || !$this->formKeyValidator->validate($this->getRequest())) {
            /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
            $resultRedirect = $this->resultRedirectFactory->create();
            //$resultRedirect->setPath('home');
            $resultRedirect->setUrl($currenturl);
            return $resultRedirect;
        }

        if ($this->getRequest()->isPost()) {
            $login = $this->getRequest()->getPost('login');
            if (!empty($login['username']) && !empty($login['password'])) {
                try {
                    $customer = $this->customerAccountManagement->authenticate($login['username'], $login['password']);
                    $this->session->setCustomerDataAsLoggedIn($customer);
                    $this->session->regenerateId();
                } catch (EmailNotConfirmedException $e) {
                    $value = $this->customerUrl->getEmailConfirmationUrl($login['username']);
                    $message = __(
                            'This account is not confirmed.' .
                            ' <a href="%1">Click here</a> to resend confirmation email.', $value
                    );
                    $this->messageManager->addError($message);
                    $this->session->setUsername($login['username']);
                } catch (AuthenticationException $e) {
                    $message = __('Invalid login or password.');
                    $this->messageManager->addError($message);
                    $this->session->setUsername($login['username']);
                } catch (\Exception $e) {
                    $this->messageManager->addError(__('Invalid login or password.'));
                }
            } else {
                $this->messageManager->addError(__('A login and a password are required.'));
            }
        }

        $resultRedirect = $this->resultRedirectFactory->create();
        //$resultRedirect->setPath('home');
        $resultRedirect->setUrl($currenturl);
        return $resultRedirect;
    }

}
Meet Shekhat
  • 181
  • 7
  • I am getting current url as http://www.testwebsite.com/customer/account/loginPost/ instead of product url – Rahul Nov 07 '19 at 09:05
  • I have edited above answer by loading product url by sku. you need to set sku for that as per your requirement. – Meet Shekhat Nov 07 '19 at 09:44
  • If I am not getting current URL so How can I get SKU of the current product page? – Rahul Nov 07 '19 at 10:10
0

If you have a plugin that receives the Magento\Customer\Controller\Account\LoginPost object you could get the referer URL like : $subject->_redirect->getRefererUrl(). Then return this URL

$productURL = $subject->_url->getUrl($subject->_redirect->getRefererUrl());
return $subject->_redirect($productURL);

I'm not 100% sure if this URL will actually be the URL you want but worth a try.

murat
  • 14
  • 3
  • Fatal error: Uncaught Error: Cannot access protected property Magento\Customer\Controller\Account\LoginPost\Interceptor::$_url in /var/www/magento/app/code/MyModule/Customization/Plugin/LoginPostPlugin.php:24 – Rahul Nov 07 '19 at 06:40
  • Right, I didnt know this property was protected. Then seems the best idea is to override LoginPost in your module and try to redirect to the referer URL there. – murat Nov 07 '19 at 09:49
  • How can we use the protected property in the plugin ? should we use constructor and override it? – Rahul Nov 07 '19 at 10:09
  • You cant use the protected property in the plugin. The solution link you provided in the original post has the example where they override the LoginPost class. – murat Nov 07 '19 at 16:16