如何设置受保护对象用户?填写表单后,我必须添加当前用户数据的用户对象(例如保存注释)。我尝试过类似的东西:
$.ajax({
method: "POST",
url: "/yourController/yourAction",
data: { name: "John", location: "Boston" }
}).done(function( data ) {
alert(JSON.Stringify(data));
});
我有这个错误
if ($form->isValid()) {
$comment = $form->getData();
$comment->user = $this->contextSecurity->getToken()->getUser();
$this->model->save($comment);
}
这是我的评论实体:
FatalErrorException: Error: Cannot access protected property AppBundle\Entity\Comment::$user in /home/AppBundle/Controller/CommentsController.php line 184
我正在使用Symfony2.3。任何帮助将不胜感激。
答案 0 :(得分:2)
您无法从对象外部修改受保护的属性。你需要一个公共财产或设置者。
class Comment
{
// ...
public function setUser(User $user)
{
$this->user = $user;
}
}
在控制器中你可以写:
$comment->setUser($this->getUser());
答案 1 :(得分:1)
这个问题与Symfony2无关,首先你应该阅读有关php类型的内容,特别是有关对象的内容。 read here然后here
您应该了解Visibility的工作原理。之后,您将了解对对象的受保护/私有属性的访问仅可从对象本身获得,因此您需要创建公共方法
setUser($user) {
$this->user = $user;
}
答案 2 :(得分:0)
我总是使用protected,如果我想编辑变量或取值,我会使用getter和setter:
public function setUser($user) {
$this->user = $user;
}
public function getUser(){
return $this->user;
}