简体   繁体   English

Symfony2 - 如何从另一个控制器渲染视图

[英]Symfony2 - How to render a view from another controller

I have two controllers, homepage and Security. 我有两个控制器,主页和安全。

In the homepage, I am displaying one view and in the security, I am doing some things, and one of them is the email address validation. 在主页中,我显示一个视图,在安全性中,我正在做一些事情,其中​​一个是电子邮件地址验证。

What I would like is that when the email validation code is not valid, display the homepage with a flash message. 我想要的是,当电子邮件验证码无效时,显示带有flash消息的主页。 For that, I will have to render the indexAction of the HomepageController, from the Security controller, by giving him as parameter the flash message. 为此,我将从安全控制器渲染HomepageController的indexAction,将其作为flash消息的参数。

How can this be done? 如何才能做到这一点? Can I render a route or an action from another controleller? 我可以从另一个控制者那里渲染一条路线或一个动作吗?

Thank you in advance. 先感谢您。

I believe the checking should not be done in the Security controller. 我认为不应该在安全控制器中进行检查。 Right place in my opinion is a separate validator service or right in the entity which uses the email address. 在我看来,正确的地方是单独的验证服务或在使用电子邮件地址的实体中的权利。

But to your question, you can call another controller's action with $this->forward() method: 但是对于你的问题,你可以用$ this-> forward()方法调用另一个控制器的动作:

public function indexAction($name)
{
    $response = $this->forward('AcmeHelloBundle:Hello:fancy', array(
        'name'  => $name,
        'color' => 'green',
    ));

    return $response;
}

The sample comes from symfony2 documentation on: http://symfony.com/doc/2.0/book/controller.html#forwarding 该示例来自symfony2文档: http ://symfony.com/doc/2.0/book/controller.html#forwarding

我找到了解决方案,只需通过指定控制器和动作nanme来使用forward函数:

return $this->forward('MerrinMainBundle:Homepage:Index', array('flash_message'=>$flash_message));

redirectToRoute : Just a recap with current symfony versions (as of 2016/11/25 with v2.3+) redirectToRoute:只是对当前symfony版本的回顾(截至2016/11/25与v2.3 +)

public function genericAction(Request $request)
{
    if ($this->evalSomething())
    {
        $request->getSession()->getFlashBag()
            ->add('warning', 'some.flash.message');
        $response = $this->redirectToRoute('app_index', [
            'flash_message' => $request->getSession()->getFlashBag(),
        ]);
    } else {
        //... other logic
    }
    return $response;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM