How to merge 2 form in Symfony2

Diego picture Diego · Aug 21, 2013 · Viewed 7.1k times · Source

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?

Answer

Cerad picture Cerad · Aug 21, 2013

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);