具有子表单和OneToMany关系的Symfony表单

时间:2016-02-16 14:43:39

标签: php symfony

存在一个主题实体,它可以包含许多注释实体,一对多。

创建Form TopicType时,嵌入了Form CommentType:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('title')
        ->add('comments', CommentType::class)
    ;
}

Symfony使用标题的输入框和Comment的输入框(例如消息)正确呈现此表单。

提交表单时会发生错误:

Neither the property "messages" nor one of the methods 
"addMessag()"/"removeMessag()", "addMessage()"/"removeMessage()", 
"setMessages()", "messages()", "__set()" or "__call()" exist and have 
public access in class "Foo\BarBundle\Entity\Topic".

在主题表单中嵌入评论表单的正确方法是什么?用户在创建主题时只能添加一个注释。

应该使用CollectionType吗?这会导致在显示Comment之前将0呈现为表单标签。 (0是附加到Thread的新Comment()的第一个索引)。

 ->add('messages', CollectionType::class)

1 个答案:

答案 0 :(得分:0)

您确实需要CollectionType::class,然后您需要一些小的javascript才能从同一表单添加多个评论。该文档解释了如何做到这一点。

http://symfony.com/doc/current/cookbook/form/form_collections.html