我在使用嵌入集合表单时遇到问题,因为我想过滤给定集合中显示的数据。即
<?php
Class Parent
{
... some attributes ...
/**
* @ORM\OneToMany(targetEntity="Child", mappedBy="parent", cascade={"all"})
*/
private $children;
... some setters & getters ...
}
Class Child
{
private $attribute1;
private $attribute2;
/**
* @ORM\ManyToOne(targetEntity="Parent", inversedBy="children")
* @ORM\JoinColumn(name="parent_id", referencedColumnName="id")
*/
private $parent;
... some setters & getters ...
}
然后我使用以下方法构建表单:
class ParentChildType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('children', 'collection', array(
'type' => ChildrenType(),
'allow_add' => true,
));
}
}
...
On controller:
$parent = $this->getDoctrine()->getEntityManager()->getRepository('AcmeBundle:Parent')->find( $id );
$forms = $this->createForm( new ParentChildType(), $parent)->createView();
and then..
return array('forms' => $forms->crateView());
我的问题是,当我想通过 Child
模型类的 $attribute1
和/或 $attribute2
过滤集合时。
有一种方法可以按此收集表单的条件进行过滤吗?
最佳答案
看来我必须在使用 CreateQuery 之前过滤对象,然后使用这个过滤后的对象创建表单。 像这样:
$parent = $this->getDoctrine()->getEntityManager()->createQuery("
SELECT p, c
FROM AcmeBundle:Parent p
JOIN p.children c
WHERE c.attribute1 = :attr1
AND c.attribute2 = :attr2
")
->setParameter('attr1', <some_value>)
->setParameter('attr2', <some_value>)
->getOneOrNullResult();
$forms = $this->createForm( new ParentChildType(), $parent)->createView();
....
return array('forms' => $form->createView());
关于forms - Symfony 2 如何使用某些标准嵌入集合表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10427557/