RydelHouse
RydelHouse

Reputation: 362

Get logged user email in entity for querybuilder - Symfony

How I can get the logged user email in entity for query builder to select items which has been created by current user?

My entity field:

->add('rfqitem', 'entity', array(
    'label'         => 'RFQ Items',
    'class'         => 'RFQ\IronilBundle\Entity\RFQItem',
    'multiple'      => true,
    'expanded'      => false,
    'attr'          => array(
        'class'         => 'rfq-item-choser'),
    'query_builder' => function ($eer){
        return $eer
            ->createQueryBuilder('a')
            ->where('a.user_email = :email')
            ->setParameter('email', 'LOGGED USER EMAIL');},
))

Create form method:

$user = $this->get('security.context')->getToken();
$form = $this->createForm(new RFQType(), $user, $entity, array(
   'action' => $this->generateUrl('rfq_create'),
   'method' => 'POST',
   'user' => $this->getUser()
));

Upvotes: 0

Views: 898

Answers (2)

Roger Guasch
Roger Guasch

Reputation: 410

Normally, I create a listener/service that returns me the logged user, and then I will call where I need

Listener

class LoggedUser {

protected $security_context;

public function __construct($securityContext){
    $this->security_context = $securityContext;
}

public function getLoggedUser(){
    return $this->security_context->get('security.context')->getToken()->getUser();
}

}

Declare the service

util.getLoggedUser:
    class: %util.getLoggedUser.listener%
    arguments: [@service_container]

And the calling:

$logged_user = $this->get('util.getLoggedUser')->getLoggedUser()

Upvotes: 1

lsouza
lsouza

Reputation: 2488

For that you will have to pass the logged in user to the form.

To pass the user as an option to your Form class, you can do this:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $user = $options['user'];

    $builder
        ->add('rfqitem', 'entity', array(
            /** other options **/
            'query_builder' => function ($eer) use ($user) {
                return $eer
                    ->createQueryBuilder('a')
                    ->where('a.user_email = :email')
                    ->setParameter('email', $user->getEmail());
            },
        ))
    ;
}

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    /** lot's of code **/

    $resolver->setRequired(array(
        'user',
    ));
}

Then, when you create the form on the controller, you pass the logged in user this way:

$form = $this->createForm(new YourFormType(), $yourObject, array('user' => $this->getUser()));

Update: For your code, it should be like this:

$user = $this->get('security.context')->getToken();
$form = $this->createForm(new RFQType(), $entity, array(
   'action' => $this->generateUrl('rfq_create'),
   'method' => 'POST',
   'user' => $user,
));

Upvotes: 1

Related Questions