How to get the given field in sonataadmin query builder?

The following code exists

$form->with('Item')->add('parent', null, array( 'label' => 'Category', 'required' => true, 'query_builder' => function($er) use ($id) { $qb = $er->createQueryBuilder('p'); if ($id){ $qb->where('p.id <> :id') ->setParameter('id', $id); } $qb->orderBy('p.root, p.lft', 'ASC'); return $qb; } ......... 

The result is a collection of entity objects that is assigned to the string (__toString method). It returns a name field. But I need to get another field - url.

How to get url value instead of name in list form? The type query_builder returns object => how to change this form so that it works similarly to query_builder?

0
source share
1 answer

I did not work with SonataAdminBundle forms, but I think it works absolutely like symfony forms. All you need to do is add the values โ€‹โ€‹of 'class' and 'property' to the parameter list:

 $form->with('Item')->add('parent', null, array( 'class' => 'Acme\DemoBundle\Entity\Category', 'property' => 'url', 'label' => 'Category', 'required' => true, 'query_builder' => function($er) use ($id) { $qb = $er->createQueryBuilder('p'); if ($id){ $qb->where('p.id <> :id') ->setParameter('id', $id); } $qb->orderBy('p.root, p.lft', 'ASC'); return $qb; } 

property is the name of the field in your entity that will represent your Entity value instead of calling __toString() . But also ... If you always need to present your Entity as a URL, you can simply redefine the __toString() method in the Entity class to something like this:

 public function __toString() { return $this->url; } 
+2
source

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


All Articles