gpt4 book ai didi

php - Symfony 2.4 app.session.flashbag.all() 返回空值

转载 作者:可可西里 更新时间:2023-11-01 12:46:51 24 4
gpt4 key购买 nike

我在使用 flashbag 消息时遇到了麻烦。我的情况很简单:

我的代码

  1. 使用表单编辑页面:

    # src/Namespace/MyBundle/Resources/views/Edit/form.html.twig
    <form action="{{ path('form_url_save', {'id': id }) }}" method="POST">
    {{ form_widget(form) }}
    </form>
  2. 通过 Controller 将数据表单保存在数据库中:

    # src/Namespace/MyBundle/Controller/EntityController.php
    public function saveAction(Request $request, Entity $entity = null) {
    try {
    if (!$entity) {
    $entity = new Entity();
    }

    $form = $this->createForm(new EntityType(), $entity);

    if ($request->getMethod() == 'POST') {
    $form->submit($request);

    if ($form->isValid()) {
    // Entity manager
    $em = $this->getDoctrine()->getManager();
    // Persist data
    $em->persist($form->getData());
    // Saving process
    $em->flush();
    // Add flashbag message
    $this->get('session')->getFlashBag()->add('success', 'The backup was done successfully'));
    } else {
    throw new \Exception($form->getErrorsAsString());
    }
    }
    } catch (\Exception $e) {
    $this->get('session')->getFlashBag()->add('error', $e->getMessage());
    }

    return $this->redirect('home_page_url');
    }
  3. 在前面显示一条成功消息:

    # app/Resources/views/front.html.twig
    <html>
    <head></head>
    <body>
    <div class="main">
    {% set flashbag = app.session.flashbag.all %}
    {% if flashbag is not empty %}
    <div class="messages-container">
    {% for type, messages in flashbag %}
    {% for message in messages %}
    <div class="alert alert-{{ type }}">
    {{ message }}
    </div>
    {% endfor %}
    {% endfor %}
    </div>
    {% endif %}

    <div class="content">
    // My content
    </div>
    </div>
    </body>
    </html>

我的主题是如何组织的?

app/Resources/views/front.html.twig
|__ src/Namespace/MyBundle/Resources/views/Edit/form.html.twig // extends front.html.twig

我的麻烦:

  • app.session.flashbag.allfront.html.twig==> Flashbag 是空的
  • app.session.flashbag.allform.html.twig 中==> Flashbag 不错,有成功消息

那么为什么我不能将代码放在 front.html.twig 中?

最佳答案

这是因为 FlashBag::all() 返回所有消息然后清空 flashes 容器。使用 FlashBag::peekAll() 方法检查 flashbag 是否包含消息。

例子:

{% if app.session.flashbag.peekAll()|length %}
{% include 'BraincraftedBootstrapBundle::flash.html.twig' %}
{% endif %}

关于php - Symfony 2.4 app.session.flashbag.all() 返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23267361/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com