Stefan Van den Heuvel
Stefan Van den Heuvel

Reputation: 124

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

Upvotes: 3

Views: 2059

Answers (1)

Waaghals
Waaghals

Reputation: 2619

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

Upvotes: 2

Related Questions