在我的表单中,我使用此代码
$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
答案 0 :(得分: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);
}
)
)