繁体   English   中英

未定义会话“setFlash”的问题 - Symfony2

[英]Issue with undefined session “setFlash” - Symfony2

我正在编写关于Symfony2的教程 (我是PHP的新手),我很难从Session对象中显示flash消息。 在我的Controller代码下面

 <?php namespace tuto\\WelcomeBundle\\Controller; use Symfony\\Bundle\\FrameworkBundle\\Controller\\Controller; class HomepageController extends Controller { public function indexAction() { $this->get('session')->setFlash('notice', 'Bienvenue à toi '.$this->get('session')->get('user_name').' !'); return $this->render('tutoWelcomeBundle:Homepage:index.html.twig'); } public function whoAmIAction($name) { # get the session $session = $this->get('session'); # store the user'name in the session $session->set('user_name', $name); return $this->redirect($this->container->get('router')->generate('tutoWelcomeBundle_homepage')); } } 

setFlash('notice', 'Bienvenue à toi '.$this->get('session')->get('user_name').' !')返回' 未定义的方法错误 '。
我确实尝试在AppKernel.php中声明它作为bundle的一部分但是找不到命名空间Symfony \\ Component \\ HttpFoundation \\ Session
在布局下面呈现它

 <div id="container"> <header> <a href="{{ path('homepage') }}" title="Retour à l'accueil">Tutoriel Symfony2</a> Bonjour et bienvenue dans ce tutoriel pour Symfony2</p> <p> {% for key, flash in app.session.getFlashes()%} {%if flash%} {{flash}} {%endif%} {%endfor%} </p> </header> <div id="content"> {% block content %}{% endblock %} </div> 

平台信息
WAMP 2.5 Symfony 2.7

由于您已经扩展了FrameworkBundle的Controller您应该可以访问名为addFlash的方法,这是在会话中添加Flash消息的快捷方式。

您可以在此处查找方法的定义。

因此,只需更换$this->get('session')->setFlash$this->addFlash ,你应该是好去。

[解]
基于[Artamiel] [2](下文)和以下[博客] [3]的反馈。
在控制器中使用$this->addFlash更改$this->get('session')->setFlash ,在TWIG模板中使用app.session.get('flashes') app.session.getFlashes() app.session.get('flashes')

注意:SF 2中不存在$session->addFlash$session->setFlash

要直接从会话对象设置flash消息(例如,如果您不在扩展SF基本控制器的控制器中),则可以使用以下方法

 $session->getFlashBag()->add('[YourType]', "[YourMessage]");

暂无
暂无

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

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