php - Symfony2 - 数组到字符串的转换异常,并带有一条闪存消息

标签 php symfony flash-message

我使用以下代码在 Controller 中设置了一个 flash 消息:

$this->get('session')->getFlashBag()->add('success', 'Message sent successfully');

在我的模板中,我使用以下内容来(尝试)显示它:

{% if app.session.flashbag.has('success') %}
    <div id="flash">
        {{ app.session.flashbag.get('success') }}
    </div>
{% endif %}

问题是,尽管 API 文档说明 get 返回一个字符串,但我得到了一个数组到字符串的转换异常。如果我将模板中的代码更改为:

{% for flashMessage in app.session.flashbag.get('success') %}
    <div id="flash">
        {{ flashMessage }}
    </div>
{% endfor %}

它工作得很好。我不想在这里使用循环,因为我只会收到或不收到一条消息。

是否有一种解决方案可以让我只检查是否存在单个闪现消息并在存在时显示它?还是我陷入了一个无用的循环?

最佳答案

通过在 0 处建立索引解决了这个问题:

{{ app.session.flashbag.get('success')[0] }}

我的怀疑是正确的——get 返回一个数组而不是一个字符串。这是 flashbag 的 add 方法:

public function add($type, $message)
{
    $this->flashes[$type][] = $message;
}

并且得到:

public function get($type, array $default = array())
{
    if (!$this->has($type)) {
        return $default;
    }

    $return = $this->flashes[$type];

    unset($this->flashes[$type]);

    return $return;
}

他们需要修复 API 文档以反射(reflect)现实。它们还应该提供一种优雅的方式来处理单个 Flash 消息。

编辑:向后兼容(PHP 5.3 及以下)版本 -

{% if app.session.flashbag.has('success') %}
    {% set flashbag = app.session.flashbag.get('success') %}
    {% set message = flashbag[0] %}
    <div id="flash">
        {{ message }}
    </div>
{% endif %}

关于php - Symfony2 - 数组到字符串的转换异常,并带有一条闪存消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15582278/

相关文章:

php - 标签和内容的搜索算法

php - Doctrine Migrations 中的回滚问题

javascript - connect-flash 和 jade : unable to show flash messahe

javascript - react 闪存消息 : How to make the message show without refreshing the page but refresh on 200

php - 如何检查字符串是否为有效的 DATE、TIME 或 DATETIME

php - sql语句中的逻辑

asp.net-mvc - ASP .NET MVC 4 中的 FormBuilder

javascript - Flash Flash 消息附加到文本区域

php - 如何在 Codeigniter 中使用文件夹?

Symfony 2 : How to render a template outside a controller or in a service?