Magento 2-登录后将客户重定向到自定义页面


9

为了在登录后将客户重定向到特定页面,我应该重写哪个类?

我试图Redirect Customer to Account Dashboard after Logging in在商店配置中进行设置,但无法正常工作。


您启用或禁用来宾结帐?
Khoa TruongDinh'9

我已禁用访客结帐。
保罗

您当前的问题如何?
Khoa TruongDinh'9

您提供的代码与我的magento有点不同。也许它来自不同的版本。而且我不明白为什么它与cookie有关。我终于通过重写LoginPost类解决了它。我在下面发布了我的答案。谢谢!
保罗

1
我的magento版本是v2.0.8
Paul

Answers:


28

在这种情况下,插件是一种更好的解决方案,因为在Magento 2更新时可能需要更新扩展类。

这是Xenocide8998建议的在LoginPost-> execute()上使用后置插件的解决方案。

/Vendor/Module/etc/frontend/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
  <type name="\Magento\Customer\Controller\Account\LoginPost">
    <plugin name="vendor_module_loginpostplugin" type="\Vendor\Module\Plugin\LoginPostPlugin" sortOrder="1" />
  </type>
</config>

/Vendor/Module/Plugin/LoginPostPlugin.php

<?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;
    }

}

1
很好 一件事是何时需要$ result-> setPath('/'); 例如,到您的自定义路径的网址不要在网址前使用“ /”。$ result-> setPath('customer / dashboard /');
Shuvankar Paul

使用插件的好方法
Hafiz Arslan,

完美的工作谢谢你
HaFiz Umer

您唯一的问题是,如果客户尝试登录并失败,那么您仍将访问主页。无法捕获失败的登录信息。
安迪·琼斯,

如何将当前页面网址传递给此插件?
拉胡尔

6

我通过重写LoginPost类解决了它

等/ di.xml

<preference for="Magento\Customer\Controller\Account\LoginPost" type="Vendor\Module\Controller\Account\LoginPost" />

供应商/模块/控制器/帐户/LoginPost.php

<?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;

/**
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class LoginPost extends \Magento\Customer\Controller\Account\LoginPost {

    public function execute() {
        if ($this->session->isLoggedIn() || !$this->formKeyValidator->validate($this->getRequest())) {
            /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
            $resultRedirect = $this->resultRedirectFactory->create();
            $resultRedirect->setPath('home');
            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');
        return $resultRedirect;
    }

}

12
我认为使用带有的插件afterExecute()将是一种更清洁的选择
Xenocide8998

2
这不是一个好方法,只会在将来引起问题。插件是必经之路。
phagento

默认情况下,我们可以从帐户仪表板重定向到销售订单历史记录页面吗?
贾法尔·品哈尔19'Sep

0

当前的本地存储导致了我们的问题。
如果我们Redirect Customer to Account Dashboard after Logging in在配置中启用或禁用“ 访客结帐”,则此功能将正常运行。但是,我们需要清除您的本地存储。

我们可以检查本地存储localStorage.getItem('mage-cache-storage')

看一看:

供应商/ magento /模块结帐/视图/前端/web/js/sidebar.js

var cart = customerData.get('cart'),
customer = customerData.get('customer');
if (!customer().firstname && cart().isGuestCheckoutAllowed === false) {
    // set URL for redirect on successful login/registration. It's postprocessed on backend.
    $.cookie('login_redirect', this.options.url.checkout);
    if (this.options.url.isRedirectRequired) {
        location.href = this.options.url.loginUrl;
    } else {
        authenticationPopup.showModal();
    }

    return false;
}

Magento将$.cookie('login_redirect', this.options.url.checkout)基于customerData本地存储设置cookie 。

从控制器vendor/magento/module-customer/Controller/Account/LoginPost.php。它将检查cookie中的重定向URL。

$redirectUrl = $this->accountRedirect->getRedirectCookie();
if (!$this->getScopeConfig()->getValue('customer/startup/redirect_dashboard') && $redirectUrl) {
    ......
    return $resultRedirect;
}

Magento版本:

-Magento版本2.1.0


0

我通过在自定义模块控制器中传递引用来解决此问题。

第一步 `

use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Customer\Model\Session;
use Magento\Framework\UrlInterface;

class Approve extends \Magento\Framework\App\Action\Action {

    /** 
    * @var \Magento\Framework\View\Result\Page 
    */
    protected $resultPageFactory;

    /** 
    * $param \Magento\Framework\App\Action\Context $context */

    /**
    * @param CustomerSession
    */

    protected $_customerSession;

    protected $_urlInterface;

    public function __construct(
        Context $context,
        PageFactory $resultPageFactory,
        Session $customerSession,
        UrlInterface $urlInterface
    )
    {
        $this->resultPageFactory = $resultPageFactory;
        $this->_customerSession  = $customerSession;
        $this->_urlInterface     = $urlInterface;
        parent::__construct($context);

    }

    public function execute(){
        $url  = $this->_urlInterface->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true]); 
// here pass custom url or you can either use current url on which you are currently and want to come back after logged in.

        $loginUrl = $this->_urlInterface->getUrl('customer/account/login', array('referer' => base64_encode($url)));
        if($this->_customerSession->isLoggedIn()){
            return $this->resultPageFactory->create();
        }
        $this->_redirect($loginUrl);
    }
}`

第2步

转到管理员:商店>配置>客户>客户配置>登录选项>登录后将客户重定向到帐户仪表板>否

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.