假设我有两个实体: apost和 a comment。每个post可以有很多comments。现在,假设我有一个评论表。它应该接受用户输入并将其存储在数据库中。
简单的东西。至少,它应该是,但我无法让它工作。
创建评论(子)时如何引用帖子(父)?我尝试手动将post_id评论表单作为隐藏字段传递,但收到一个错误,抱怨帖子 ID 是一个字符串。
Expected argument of type "App\Entity\Post or null", "string" given.
到目前为止,这是我的代码。有人可以将我推向正确的方向吗?
评论类型.php
public function buildForm(FormBuilderInterface $builder, array $options)
{
$post_id = $options['post_id'];
$builder->add('content', TextareaType::class, [
'constraints' => [
new Assert\NotBlank(['message' => 'Your comment cannot be blank.']),
new Assert\Length([
'min' => 10,
'minMessage' => 'Your comment must be at least {{ limit }} characters long.',
]),
],
])->add('post', HiddenType::class, ['data' => $post_id]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Comment::class,
'post_id' => NULL,
]);
}
PostController.php(这是评论表单出现的地方)
// Generate the comment form.
$comment = new Comment();
$form = $this->createForm(CommentType::class, $comment, [
'action' => $this->generateUrl('new_comment'),
'post_id' => $post_id,
]);
评论控制器.php
/**
* @param Request $request
* @Route("/comment/new", name="new_comment")
* @return
*/
public function new(Request $request, UserInterface $user)
{
// 1) Build the form
$comment = new Comment();
$form = $this->createForm(CommentType::class, $comment);
// 2) Handle the submit (will only happen on POST)
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
// 3) Save the comment!
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($comment);
$entityManager->flush();
}
return $this->redirectToRoute('homepage');
}
非常感谢您的帮助!