且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Symfony2中合并2格式

更新时间:2022-11-12 11:35:07

制作一个包含两个子表单的表单类型。

  class MergedFormType 

$ builder-> add('topic',new TopicFormType());
$ builder-> add('post',new PostFormType());

在你的控制器中传递一个数组到MergedFormType

  public function myAction()

$ formData ['topic'] = $ topic;
$ formData ['post'] = $ post;

$ form = $ this-> createForm(new MergedFormType(),$ formData);


I'm trying to create a very simple forum with Symfony2.

My entities are: ForumCategory (name, description...) ForumTopic (category_id, title) ForumPost (isFirstPost, body, topic_id, author_id...)

When a user try to create a Topic, I want to display only one form in the same page to create a Topic and the first post message. Like:

  • Insert topic title: ...
  • Insert topic body (related Post Body): ...

[...]

How can I do that? It's possible merge two form in this case?

Make a form type that contains both of your sub forms.

class MergedFormType

    $builder->add('topic', new TopicFormType());
    $builder->add('post',  new PostFormType());

In your controller just pass an array to MergedFormType

public function myAction()

    $formData['topic'] = $topic;
    $formData['post']  = $post;

    $form = $this->createForm(new MergedFormType(), $formData);