使用Symfony2在Twig中进行多对多检查

时间:2015-05-20 07:03:22

标签: symfony many-to-many twig

编辑时我需要检查已经有关系的盒子,我想出了这个解决方案:

{% for c in categories %}
    {% set checked = false %}
    {% for p in c.posts %}
        {% if p.id == post.id %}
            {% set checked = true %}
        {% endif %}
    {% endfor %}
    <input type='checkbox' value='categories[{{ c.id }}]'{% if checked %} checked='checked'{% endif %}>{{ c.name }}
{% endfor %}

它可以工作,但可以更好的方式完成吗?

2 个答案:

答案 0 :(得分:3)

您可以使用contains()集合方法:

{% for c in categories %}
    <input type='checkbox' value='categories[{{ c.id }}]'{% if c.posts.contains(post) %} checked='checked'{% endif %}>{{ c.name }}
{% endfor %}

答案 1 :(得分:0)

我认为这可行: 在php:

$catIds = [];
foreach($post->getCategories() as $cat){
  $catIds[] = $cat->getId();
}

将此$catIds传递给twig,然后将其传递给twig:

{% for c in categories %}
    <input type='checkbox' value='categories[{{ c.id }}]'
        {% if c.id in catIds %} checked='checked'{% endif %}
    />
    {{ c.name }}
{% endfor %}