0

I want to store user id of user who is creating/editing content into the database. I already created the entity.

How to add the user field in my controller to entity

What do I change at this point

    $entity  = new Product();
    $form = $this->createForm(new ProductType(), $entity);
    $form->bind($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($entity);
        $em->flush();

User Part of Product Entity

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

/**
 * Set user
 *
 * @param \CJ\BusinessBundle\Entity\User $user
 * @return Product
 */

public function setUser(\CJ\BusinessBundle\Entity\User $user = null)
{
    $this->user = $user;

    return $this;
}
chirag7jain
  • 1,485
  • 3
  • 26
  • 43

1 Answers1

3

You would get the current user using $this->get('security.context')->getToken()->getUser().

Then just after declaring your entity you would add the user or user_id.

So..

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

$entity = new Product();
$entity->setUser($user);
    // or $entity->setUserid($user->getId()) or maybe something
    // else depending on your entity

When you then create your form using the entity the user (or userid) would be part of it.

qooplmao
  • 17,622
  • 2
  • 44
  • 69