Add a query/filter to sonata_type_collection

安稳与你 提交于 2019-12-11 03:13:25

问题


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 ProductVariants.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!