简体   繁体   中英

Sonata Admin custom query in configureListFields

I am stuck on this for several hours.

I have admin class to list all categories and in one table column there are related products (Product entity): Table example Related code:

protected function configureListFields(ListMapper $listMapper)
{
    $listMapper
            ->addIdentifier('name')
            ->add('products') // Entity Product, @ORM\OneToMany
            ->add('ord')
    ;
}

What I need to do is hide inactive products from being listed based on "(boolean) product.active" but I can't figure it out. I know about "createQuery" method but it doesn't work. When I generate SQL and run the query directly it works but here it looks like I can use ProxyQuery only to filter Category and then all Products are queried in separate query (and this separate query I am not sure how to change).

public function createQuery($context = 'list')
{
    $query = parent::createQuery($context);

    $q = new ProxyQuery($query->join(sprintf('%s.products', $query->getRootAlias()), 'p')
            ->andWhere('p.active = :act')->setParameter('act', true));

    return $q;
}

Thank you for any help

You can change the type of your field to null or entity and add a query_builder option to adapt the query used :

protected function configureListFields(ListMapper $listMapper)
{
    $listMapper
        ->addIdentifier('name')
        ->add('products', null, array(
            'query_builder' => function(EntityRepository $er) {
                 return $er->createQueryBuilder('qb')
                           ->leftjoin('qb.products', 'p')
                           ->where('p.active = :act')
                           ->setParameter('act', true)
             }
     ));
}

I didn't test it with a oneToMany relation.

There are some information in this topic

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