简体   繁体   中英

Use current user id - symfony 2

I use the FOS User bundle and LdapBundle for my users to connect to the website. I created a form, and I want to keep a track on who added an entry. So I want to save to the database the user that added/modified that thing.

What is the best way to do this ? Since it's going to be a form, my first thought was to create an hidden field on my FormType with the current user id, but I think it's safe.

Any suggestion would be appreciated.

Thanks !

I would suggest against the hidden field as it could be easily manipulated.

The better way would be to inject SecurityContext into your form and bind the logged in user to that object via POST_SUBMIT event.

I dont know ldapBundle but when i want to save for example a photo i do in my controller

    $user=$this->security_context->getToken()->getUser();

    $form = $this->createForm(new PhotoType(), $photo )
    $request = $this->get('request');

    if ($request->getMethod() == 'POST') {

                $form->handleRequest($request);

                if ($form->isValid()) {

                   $photo->setUser($user);

                   $em = $this->getDoctrine()->getManager();
                   $em->persist($photo);
                   $em->flush();

            ....


Its a basic code, you also have to check if the user exist beofre doing the persistance : if($user) ...

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