0

在我的表格中,我使用此代码

$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');
                            }
            )
    );

我想

如果用户角色ROLE_ADMIN运行此代码并显示所有用户(此代码执行此操作)

如果用户角色是ROLE_USER此代码,则仅在列表中显示经过身份验证的用户

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

错误 我检查此代码并返回错误:

 $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
4

1 回答 1

3

解决方案:

$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);
                        }
        )
)
于 2013-04-26T05:35:38.117 回答