Search code examples
symfonydoctrine-ormfosuserbundlefr3dldapbundle

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 !


Solution

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