问题
I have an entity "Product" which has a OTM relation with "ProductVariant".
I would like to be able to generate a sonata_type_collection wherein only the ProductVariants with "isMaster = false" are shown.
I can't use the query_builder in the sonata_type_collection. Is there another way of manipulating the generated list and still be able to insert new ProductVariants into the Product entity?
My entities:
/**
* Product
*
* @ORM\Table(name="product")
* @Gedmo\SoftDeleteable(fieldName="deletedAt")
* @ORM\Entity
*/
class Product
{
/**
* @var ArrayCollection $variants
* @ORM\OneToMany(targetEntity="My\Bundle\ProductVariant", mappedBy="product", cascade={"all"}, orphanRemoval=true)
*/
private $variants;
}
/**
* ProductVariant
*
* @ORM\Table(name="productVariant")
* @Gedmo\SoftDeleteable(fieldName="deletedAt")
* @ORM\Entity
*/
class ProductVariant
{
/**
* @var Product
* @ORM\ManyToOne(targetEntity="My\Bundle\Product", inversedBy="variants")
*/
private $product;
}
The ProductAdmin:
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('variants', 'sonata_type_collection',
array(
'label' => 'A nice label',
'btn_add' => false, // Because adding won't work with the softdeletable variants
'type_options' => array(
'delete' => true,
)
),
array(
'edit' => 'inline',
'inline' => 'table',
'delete' => 'inline'
)
)
;
}
回答1:
You could create different getters and setters for the different types of ProductVariant
s.
My\Bundle\Product
public function getNonMasterVariants() {
return $this->variants->filter(function(My\Bundle\ProductVariant $item) {
return !$item->isMaster();
});
}
public function getMasterVariants() {
return $this->variants->filter(function(My\Bundle\ProductVariant $item) {
return $item->isMaster();
});
}
ProductAdmin
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('nonMasterVariants', 'sonata_type_collection',
array(
...
),
array(
...
)
)
;
}
来源:https://stackoverflow.com/questions/28317211/add-a-query-filter-to-sonata-type-collection