跳到内容

故障排除

编辑此页

toString 方法

有时 bundle 需要显示您的模型对象,为了实现这一点,对象会使用 __toString__ 魔术方法转换为字符串。请注意,在此方法中永远不要返回字符串以外的任何内容。例如,如果您的方法如下所示

1
2
3
4
5
6
7
8
9
// src/Entity/Post.php

class Post
{
    public function __toString()
    {
        return $this->getTitle();
    }
}

您不能确定您的对象在 bundle 想要将其转换为字符串时 总是 具有标题。因此,为了避免任何致命错误,您必须在标题缺失时返回一个空字符串(或任何您喜欢的),就像这样

1
2
3
4
5
6
7
8
9
// src/Entity/Post.php

class Post
{
    public function __toString()
    {
        return $this->getTitle() ?: '';
    }
}

大型过滤器和长 URL 问题

如果您尝试向单个 admin 类添加数百个过滤器,您会遇到一个问题 - 生成的过滤器表单 URL 非常长。在大多数情况下,您会收到类似 Error 400 Bad RequestError 414 Request-URI Too Long 的服务器响应。根据 StackOverflow 讨论,“安全”的 URL 长度约为 2000 个字符。您可以通过在您的编辑模板中添加一小段 JQuery 代码来解决此问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$(function() {
    // Add class 'had-value-on-load' to inputs/selects with values.
    $(".sonata-filter-form input").add(".sonata-filter-form select").each(function(){
        if($(this).val()) {
            $(this).addClass('had-value-on-load');
        }
    });

    // REMOVE ALL EMPTY INPUT FROM FILTER FORM (except inputs, which has class 'had-value-on-load')
    $(".sonata-filter-form").submit(function() {
        $(".sonata-filter-form input").add(".sonata-filter-form select").each(function(){
            if(!$(this).val() && !$(this).hasClass('had-value-on-load')) {
                $(this).remove()
            };
        });
    });
});
本作品,包括代码示例,根据 Creative Commons BY-SA 3.0 许可协议获得许可。
目录
    版本