0

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
4
  • 1
    Have you considered using the Form Events? Commented Apr 25, 2013 at 19:09
  • no, I define $form = $this->createForm....()->add(...)->getForm(); Commented Apr 25, 2013 at 19:19
  • Your question is about asking how to access the role of the user then? Commented Apr 25, 2013 at 19:28
  • If user role is ADMIN show in ComboBox all user, else if user role is USER show in ComboBox just Authenticated User Commented Apr 25, 2013 at 19:32

1 Answer 1

3

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);
                        }
        )
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.