简体   繁体   中英

Add a query/filter to sonata_type_collection

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'
            )
        )
    ;
}

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(
                ...
            )
        )
    ;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM