如何筛选Symfony2表单集合中显示的实体

时间:2015-07-14 05:54:46

标签: forms symfony

有没有办法过滤表格集合中Symfony2收集的实体?

我的情况是这样的;

2个实体:父母和孩子。 子实体有一个属性'birthdate'。 两个表之间存在许多关系。

我有一个formType(parentType),它包含一组childType表单。

我可以加载parentType,并加载与父记录关联的每个childType。

我想过滤childType集合,以便包含生日日期大于日期的记录,并排除小于日期的记录。

Symfony2集合表单类型不允许使用'query_builder'来过滤builder-> add()中的选择。

有没有人遇到或解决过这个问题?

1 个答案:

答案 0 :(得分:3)

我的解决方案是使用单独的setter / getter进行子实体收集,并使用Criteria过滤getter输出。表单字段名称应为“filteredChilds”。有点hacky但应该做的伎俩。

实体/ Parent.php

<?php

...

use Doctrine\Common\Collections\Criteria;

...

class Parent
{

    ...

    /**
     * @param Child $child
     * @return $this
     */
    public function addChild(Child $child)
    {
        $this->childs[] = $child;

        return $this;
    }

    /**
     * @param Child $child
     */
    public function removeChild(Child $child)
    {
        $this->childs->removeElement($child);
    }

    /**
     * @return ArrayCollection
     */
    public function getChilds()
    {
        return $this->childs;
    }

    /**
     * @param Child $child
     * @return $this
     */
    public function addFilteredChild(Child $child)
    {
        $this->addChild($child);
    }

    /**
     * @param Child $child
     */
    public function removeFilteredChild(Child $child)
    {
        $this->removeChild($child);
    }

    /**
     * @return ArrayCollection
     */
    public function getFilteredChilds()
    {
        $criteria = Criteria::create()
            ->where(Criteria::expr()->gt("birthday", new \DateTime()));

        return $this->getChilds()->matching($criteria);
    }

    ...

}
相关问题