magento 2中的重定向控制器


15

我在客户仪表板中添加了一个新的自定义选项卡。如果我的自定义表单成功执行,则需要重定向到客户主页customer/account。我怎样才能做到这一点?

Answers:



21

使用以下代码:

protected $resultRedirect;

public function __construct(\Magento\Framework\Controller\ResultFactory $result){
   $this->resultRedirect = $result;
}

public function execute()
{
    $resultRedirect = $this->resultRedirect->create(ResultFactory::TYPE_REDIRECT);
    $resultRedirect->setUrl($this->_redirect->getRefererUrl());

    return $resultRedirect;         
 }  

希望它对您和其他人有帮助。


1
你我的朋友现在是我的上帝,我每晚向你祈祷!谢谢!节省了我很多时间。
OZZIE

14
public function execute()
{
$resultRedirect = $this->resultRedirectFactory->create();
$resultRedirect->setPath('routename/controllerpath/controllername');
return $resultRedirect;
}

无需在构造中声明$ this-> resultRedirectFactory,因为它在您的自定义控制器应扩展到的\ Magento \ Framework \ App \ Action \ Action构造中声明为自动。否则在编译过程中会出错:resultRedirectFactory已经声明


2

试试这个代码:

 namespace Company\Module\Controller\Index;
    use Magento\Framework\Controller\ResultFactory; 

    class Actionname name extends \Magento\Framework\App\Action\Action
    {      
        public function execute()
        {
            $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);

            // Your code

            $resultRedirect->setUrl($this->_redirect->getRefererUrl());
            return $resultRedirect;
        }
    }

2
$resultRedirect = $this->resultRedirectFactory->create();
$this->messageManager->addNotice(__("Login Reuqire For Edit Post. So Please <i class='fa fa-lock'></i> Login Now And Edit Your Post."));
$customerBeforeAuthUrl = $this->_url->getUrl('customer/account/login', array('referer' => $objecturl->getEncodedUrl($this->_url->getUrl(''))));
return $resultRedirect->setPath($customerBeforeAuthUrl);

试试这个代码,我希望你可以使用它:)


1
$this->_url->getUrl()对我来说,使用缺少的细节,谢谢!
cjohansson

0

在控制器中尝试以下代码以重定向到上一页:

<?php
namespace Vendor\Module\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action {
    protected $_pageFactory;

    /**
     * @var \Magento\Framework\Session\SessionManagerInterface
     */
    protected $_sessionManager;

    public function __construct(
        \Magento\Framework\App\Action\Context $context      

    ) {
        $this->resultFactory = $context->getResultFactory();

        return parent::__construct($context);
    }

    public function execute()
    {


        $resultRedirect = $this->resultRedirectFactory->create();
        $url = $this->_redirect->getRefererUrl();

        $resultRedirect->setUrl($url);
        return $resultRedirect;
    }
}

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.