Sonata Admin custom request in configureListFields

I was stuck on this for several hours.

I have an admin class for all categories and in one column of the table there are related products (Product entity): Example table Related code:

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

What I need to do is to hide inactive products from a list based on "(boolean) product.active", but I cannot figure it out. I know about the createQuery method, but it does not work. When I create SQL and run the query directly, it works, but it looks like I can use ProxyQuery only to filter the category, and then all the products are requested in a separate query (and this separate query I'm 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; } 

Thanks for any help

+5
source share
1 answer

You can change the type of the field to zero or an entity and add the query_builder parameter 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 have not tested it with the oneToMany attitude.

There is some information in this thread.

+1
source

Source: https://habr.com/ru/post/1234336/


All Articles