gan
gan

Reputation: 3099

Symfony2 add current user to form input data

I've got a standard FOS user that's got a ManyToOne entity relationship with a blog entity.

/**
 * @ORM\ManyToOne(targetEntity="User", inversedBy="blog")
 * @ORM\JoinColumn(name="user", referencedColumnName="id")
 */
private $user;

I've used the app/console generate:doctrine:crud command to generate a basic crud system.

When I create a new blog entity I want to insert the logged in user that performed the action. By default Symfony generates CRUD code that allows the user to select which user is connected to the entity.

    $builder
        ->add('name')
        ->add('address')
        ->add('facebook')
        ->add('twitter')
        ->add('user')
    ;

In the controller I can access the logged in user using security.context:

$user = $this->get('security.context')->getToken()->getUser();

Whats the best course of action to change this?

Upvotes: 2

Views: 1464

Answers (1)

gan
gan

Reputation: 3099

Okay! solved my own question (if I'm doing it wrong please feel free to correct me, and I'll accept a better answer). This one does appear to work well however!

The user can be added in the controller after the $form->isValid() check is performed. Here's my controller function for example.

public function createAction(Request $request)
{
    $entity  = new Blog();
    $form = $this->createForm(new BlogType(), $entity);
    $form->bind($request);

    if ($form->isValid()) {
        $entity->setUser($this->get('security.context')->getToken()->getUser());
        $em = $this->getDoctrine()->getManager();
        $em->persist($entity);
        $em->flush();
        return $this->redirect($this->generateUrl('blog_show', array('id' => $entity->getId())));
    }

    return $this->render('ExampleBundle:Blog:new.html.twig', array(
        'entity' => $entity,
        'form'   => $form->createView(),
    ));
}

The user needs to be removed from the form builder for this to work.

Upvotes: 5

Related Questions