How can I set the protected object user? After filling the form i have to add user object with current user data (for example like saving comments). I tried something like that:
if ($form->isValid()) {
$comment = $form->getData();
$comment->user = $this->contextSecurity->getToken()->getUser();
$this->model->save($comment);
}
And i've got this error
FatalErrorException: Error: Cannot access protected property AppBundle\Entity\Comment::$user in /home/AppBundle/Controller/CommentsController.php line 184
Here is my Comment entity:
class Comment
{
/**
* Id.
*
* @ORM\Id
* @ORM\Column(
* type="integer",
* nullable=false,
* options={
* "unsigned" = true
* }
* )
* @ORM\GeneratedValue(strategy="IDENTITY")
*
* @var integer $id
*/
private $id;
/**
* Content.
*
* @ORM\Column(
* name="content",
* type="string",
* length=250,
* nullable=false
* )
* @Assert\NotBlank(groups={"c-default"})
* @Assert\Length(min=3, max=250, groups={"c-default"})
*
* @var string $content
*/
private $content;
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="comments")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
*/
protected $user;
I'm using Symfony2.3. Any help will be appreciated.
You can't modify protected properties from outside of the object. You need a public property or a setter for that.
class Comment
{
// ...
public function setUser(User $user)
{
$this->user = $user;
}
}
And in a controller you can write:
$comment->setUser($this->getUser());