Reputation: 149
Is there a way to filter the entities collected by Symfony2 in a form collection?
My scenario is this;
2 entities: parent and child. The child entity has a property 'birthdate'. There is a manyToMany relationship between the 2 tables.
I have a formType (parentType) that contains a collection of childType forms.
I can load parentType and it loads every childType that is associated to the parent record.
I want to filter the childType collection so that records with a birthdate greater than a date are included and those less than the date are excluded.
The Symfony2 collection form type does not allow the use of 'query_builder' to filter the selection in builder->add().
Has anyone faced or solved this problem?
Upvotes: 1
Views: 894
Reputation: 4345
My solution is to use separate setter/getter for child entity collection and filter getter output with Criteria. Form field name should be "filteredChilds". A bit hacky but should do the trick.
Entity/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);
}
...
}
Upvotes: 3