0

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 !

Anthony
  • 804
  • 3
  • 12
  • 32

2 Answers2

1

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.

Jovan Perovic
  • 19,846
  • 5
  • 44
  • 85
1

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) ...

oligan
  • 634
  • 6
  • 18
  • Thanks for the answer. I can't get `$user=$this->security_context ...` working, PHPStorm keep telling me the field `security_context` does not exist it my controller. What do I have to include ? – Anthony Nov 14 '14 at 17:09