TaK*_*kEr 7 php session symfony twig
我在使用flashbag消息时遇到了麻烦.我的情况很简单:
使用表单编辑页面:
# src/Namespace/MyBundle/Resources/views/Edit/form.html.twig
<form action="{{ path('form_url_save', {'id': id }) }}" method="POST">
{{ form_widget(form) }}
</form>
Run Code Online (Sandbox Code Playgroud)通过控制器将数据表单保存在数据库中:
# 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');
}
Run Code Online (Sandbox Code Playgroud)在前面显示成功的消息:
# 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>
Run Code Online (Sandbox Code Playgroud)app/Resources/views/front.html.twig
|__ src/Namespace/MyBundle/Resources/views/Edit/form.html.twig // extends front.html.twig
Run Code Online (Sandbox Code Playgroud)
app.session.flashbag.all
in front.html.twig
==> Flashbag为空app.session.flashbag.all
在form.html.twig
==> Flashbag很好,并有成功的消息那么为什么我不能把代码放在front.html.twig
?
b.b*_*4rd 13
这是因为FlashBag::all()
返回所有消息然后清空闪存容器.使用FlashBag::peekAll()
方法检查flashbag是否包含消息.
例:
{% if app.session.flashbag.peekAll()|length %}
{% include 'BraincraftedBootstrapBundle::flash.html.twig' %}
{% endif %}
Run Code Online (Sandbox Code Playgroud)
我刚刚偶然发现了同样的问题并发现了这个:Symfony2 FlashBag在升级到2.4后停止工作?
如果其他主题没有回答您的问题,您可能需要尝试转储 Flashbag 以查看其结构。这样做,尝试将其添加到您的树枝模板中:
{% set array = app.session.flashbag.all %}
{% dump(array) %}
Run Code Online (Sandbox Code Playgroud)
你可能会对结果感到惊讶,至少我是这样:
array(1) { ["test"]=> array(1) { [0]=> string(28) "Ceci est un test de flashbag" } }
Run Code Online (Sandbox Code Playgroud)
这意味着您的闪存包中确实有消息,但您无法以正确的方式获取内容,因为它位于第二个数组中。我的解决方案:
{% for tag, line in array %}
{% for underline in line %}
<div class="{{tag}}">{{ underline }}</div>
{% endfor %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助
归档时间: |
|
查看次数: |
5070 次 |
最近记录: |