简体   繁体   中英

Symfony2: Pass Parameter to Form entity object for query_builder

In My form i use this code

$form->add('user', 'entity', 
        array(
                'label' => 'User Name',
                'class' => 'DotArtBundle:User',
                'property' => 'name',
                'query_builder' => function(EntityRepository $er){
                                return $er->createQueryBuilder('u')->where('u.type = 1');
                            }
            )
    );

I want

if user role is ROLE_ADMIN run this code and show all user (This code do this)

if user role is ROLE_USER this code only show authenticated user in list

  'query_builder' => function(EntityRepository $er){
         return $er->createQueryBuilder('u')->where('u.type = 1 and u.id = ' . $this->getUser()->getId());
    }

Error I check this code and return error:

 $where  = 'u.id = '.$userid;
 $form = $this->createFormBuilder($poduct)
              ->add('user', 'entity', 
                      array(
                        'label' => 'نانم کاربری',
                        'class' => 'DotArtBundle:User',
                        'property' => 'name',
                        'query_builder' => function(EntityRepository $er){
                                               return $er->createQueryBuilder('u')->where($where);
                                                }
                                )
                        )
Notice: Undefined variable: where in C:\xampp\htdocs\ArtGirl\src\Dot\ArtBundle\Controller\ProductController.php line 38

Solution:

$where  = '';
$userid = $this->getUser()->getId();
if (!$this->get('security.context')->isGranted('ROLE_ADMIN')){
    $where = ' and u.id = ' . $userid;
}


$form->add('user', 'entity', 
    array(
            'label' => 'نانم کاربری',
            'class' => 'DotArtBundle:User',
            'property' => 'name',
            'query_builder' => function(EntityRepository $er) use ($where){
                            return $er->createQueryBuilder('u')->where('u.type = 1 '.$where);
                        }
        )
)

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