我在使用Flashbag消息时遇到了麻烦。我的情况很简单:
我的密码
# src/Namespace/MyBundle/Resources/views/Edit/form.html.twig
<form action="{{ path('form_url_save', {'id': id }) }}" method="POST">
{{ form_widget(form) }}
</form>
# 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');
}
# 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.all
==> Flashbag为空front.html.twig
==> Flashbag很好,并且收到了成功消息那么,为什么我不能将代码放在
app.session.flashbag.all
中呢? 最佳答案
我偶然发现了相同的问题,发现了这个问题:Symfony2 FlashBag stopped working after upgrade to 2.4?
如果其他主题没有回答您的问题,您可能想要尝试丢弃您的Flashbag来查看其结构。这样做,请尝试将其添加到 Twig 模板中:
{% set array = app.session.flashbag.all %}
{% dump(array) %}
您可能会对所发生的事情感到惊讶,至少我一直在:
array(1) { ["test"]=> array(1) { [0]=> string(28) "Ceci est un test de flashbag" } }
这意味着您的闪光灯袋中确实有消息,但由于内容在第二个数组中,因此您无法以正确的方式获取内容。我的解决方案:
{% for tag, line in array %}
{% for underline in line %}
<div class="{{tag}}">{{ underline }}</div>
{% endfor %}
{% endfor %}
希望这可以帮助