我有回复表单设置回复帖子。
我想将作者设置为当前登录的用户。现在它只是已经发布的以前作者的下拉菜单,这不是我想要的。
如何将其设置为使用当前登录的用户名作为作者而不是已将作者列表保存到数据库?
是否有全局命令访问当前登录的用户以传入表单中的->add('author)
行?
ReplyType表单
class ReplyType extends AbstractType
{
/**
* {@inheritDoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('author')
->add('body')
->add('post', 'submit');
}
/**
* {@inheritDoc}
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme\DemoBundle\Entity\Reply'
));
}
/**
* {@inheritDoc}
*/
public function getName()
{
return 'acme_demobundle_reply';
}
}
回复实体
/**
* @var Author
*
* @ORM\ManyToOne(targetEntity="Author", inversedBy="replies")
* @ORM\JoinColumn(name="author_id", referencedColumnName="id", nullable=false)
* @Assert\NotBlank
*/
private $author;
答案 0 :(得分:4)
由于登录用户是作者,如何删除该字段并将作者设置为控制器内当前登录的用户?用户实际上不应该选择作者(即:请参阅Stackoverflow.com回复或评论表单)。
// ...
use Symfony\Component\HttpFoundation\Request;
public function postReplyAction(Request $request)
{
$reply = new Reply();
$form = $this->createForm(new ReplyType(), $reply);
$form->handleRequest($request);
if ($form->isValid()) {
// perform your logic and before savig the reply to the database
$reply->setAuthor($this->getUser());
// save your reply
return $this->redirect($this->generateUrl('reply_success'));
}
// ...
}
您的表单类型变为:
class ReplyType extends AbstractType
{
/**
* {@inheritDoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('body')
->add('post', 'submit');
}
/**
* {@inheritDoc}
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme\DemoBundle\Entity\Reply'
));
}
/**
* {@inheritDoc}
*/
public function getName()
{
return 'acme_demobundle_reply';
}
}