How to get the defined field in sonataadmin query builder?

喜夏-厌秋 提交于 2019-12-23 04:27:03

问题


There is the following code

    $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;
                                         }
                                       .........

Result is the entity-objects collection which is given to the string (__toString method). It return name-field. But I need get the another field - url.

How to get url value instead the name in the select-list form? The query_builder type return object => how to change this form that it works likewise query_builder?


回答1:


I didn't work with SonataAdminBundle forms, but I think that it works absolutely like symfony forms. All that you need here is to add 'class' and 'property' values to your options 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's value instead of calling __toString(). But also... If you need always represent your Entity as URL you can simply override __toString() method in the Entity class to something like that:

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


来源:https://stackoverflow.com/questions/22013504/how-to-get-the-defined-field-in-sonataadmin-query-builder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!