【问题标题】:Symfony 2.1 app.session.flashbag.get('something') returns empty valueSymfony 2.1 app.session.flashbag.get('something') 返回空值
【发布时间】:2012-09-25 08:12:20
【问题描述】:

我在使用app.session.flashbag.get('notice') 时遇到问题。

在我制作的控制器中

public function updateAction(Request $request, $id)
{
    $em = $this->getDoctrine()->getManager();

    $entity = $em->getRepository('SomeBundle:SomeEntity')->find($id);

    $editForm = $this->createForm(new SomeEntityType(), $entity);
    $editForm->bind($request);

    if ($editForm->isValid()) {
        $em->persist($entity);
        $em->flush();

        $flash = $this->get('translator')->trans('Some Entity was successfully updated');
        $this->get('session')->getFlashBag()->add('notice', $flash);

        return $this->redirect($this->generateUrl('some_entity_edit', array('id' => $id)));

    }

在 editAction 中,我从会话中获取信息:

public function editAction($id)
{
    $em = $this->getDoctrine()->getManager();

    $flashes = $this->get('session')->getFlashBag()->get('notice', array());

    //...
    //...

    return array(
        'entity'      => $entity,
        'edit_form'   => $editForm->createView(),
        'flashes' => $flashes
    );
}

我正在尝试在 TWIG 中从会话中获取信息:

TWIG: {% for flashMessage in app.session.flashbag.get('notice') %}{{ flashMessage }}{% endfor %}

PHP: {% for flashMessage2 in flashes %}{{ flashMessage2 }}{% endfor %}

app.session.flashbag.get('notice') 为空,flash 有值。

您有什么想法,为什么我无法从 app.session.flashbag.get('notice') 获取数据?

【问题讨论】:

标签: php session symfony


【解决方案1】:

它的正常行为。您首先访问控制器中的闪存,然后将其返回并取消设置。当您再次访问它时,闪存包中不存在密钥,这种方式是空的。

在 github 上查看 FlashBag::get

【讨论】:

  • 谢谢你的回答,我不知道。但问题是,在我添加代码以从 PHP 控制器中的会话中检索信息之前。它适用于 Symfony 2.1.1,但在将 Symfony 更新到 2.1.2 后闪烁消失了
  • @yashchar 确实很奇怪,IRC 这种行为已经很老了(肯定是在所有 2.1.x 版本中)。
【解决方案2】:

使用FlashAlertBundle 可以轻松处理(添加/显示)Symfony flash 消息,它是使用纯 JavaScript 实现的独立 Symfony2 包,因此您不必担心使用JS 库。

您只需要以下代码即可在您的 twig 模板上呈现 flash 消息:

{{ render_flash_alerts() }}

可通过
https://github.com/rasanga/FlashAlertBundle
https://packagist.org/packages/ras/flash-alert-bundle

获得

【讨论】:

    猜你喜欢
    • 2019-05-15
    • 2014-06-09
    • 1970-01-01
    • 1970-01-01
    • 2018-04-03
    • 2020-06-02
    • 2012-09-18
    • 2017-08-25
    • 2017-04-04
    相关资源
    最近更新 更多