6

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?

Diego
  • 215
  • 1
  • 7
  • 14

3 Answers3

15

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);
Cerad
  • 48,157
  • 8
  • 90
  • 92
  • I've done this, but am getting the error "This form should not contain extra fields" when I submit fields that are in one of the nested forms. any ideas? – StampyCode Sep 02 '15 at 15:37
  • 1
    Using symfony/form 3.* I get `Expected argument of type "string"` in MergedFormType. Any ideas how to solve this? – Keloo Feb 07 '16 at 13:14
  • Have you checked the docs? S3 no longer supports passing an instance of a form type. One of several significant form changes. – Cerad Feb 07 '16 at 15:08
  • 1
    For symfony3 take a look here: http://stackoverflow.com/questions/35254110/how-to-merge-and-handle-2-symfony-forms-in-one – Keloo Feb 08 '16 at 19:00
  • @Cerad can you give a hand here? http://stackoverflow.com/questions/35343751/initialize-custom-type-form-data, I'm doing the same you proppose... but didn't worked for me. $formData is not recognized. – Pipe Feb 11 '16 at 20:07
1

Incase if you are looking to merge forms for 2 entities with one to many or one to one relationship; you will need to use form collection extension of symfony 2 component. for eg: where Task entity has many Tags

class TaskType extends AbstractType 
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('description');

        $builder->add('tags', 'collection', array('type' => new TagType()));
    }

Rendering can be done this way

{{ form_start(form) }}
   <h3>Tags</h3>
   <ul class="tags">
       {# iterate over each existing tag and render its only field: name #}
       {% for tag in form.tags %}
           <li>{{ form_row(tag.name) }}</li>
       {% endfor %}
   </ul>

Further details: http://symfony.com/doc/2.7/cookbook/form/form_collections.html

SudarP
  • 906
  • 10
  • 12
0

You can also map the same entity to multiple merged forms.

    $entity = new Form();

    $form = $this->get('form.factory')->create(FormType::class, [
        'form_builder' => $entity,
        'submit_builder' => $entity,
    ]);

FormType.php

<?php

namespace GenyBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type;
use Symfony\Component\OptionsResolver\OptionsResolver;
use GenyBundle\Entity\Form;

class FormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
           ->add('form_builder', FormBuilderType::class, [
               'data_class' => Form::class,
               'label' => false, // Important!
           ])
           ->add('submit_builder', SubmitBuilderType::class, [
               'data_class' => Form::class,
               'label' => false,
           ])
           ->add('save', Type\SubmitType::class, [
               'label' => 'geny.type.form.save.label',
           ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'translation_domain' => 'geny',
        ]);
    }
}

FormBuilderType.php

<?php

namespace GenyBundle\Form\Type;

use GenyBundle\Base\BaseType;
use Symfony\Component\Form\Extension\Core\Type;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class FormBuilderType extends BaseType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
           ->add('title', Type\TextType::class, [
               'attr' => [
                   'placeholder' => 'geny.type.form.title.placeholder',
               ],
               'empty_data' => $this->get('translator')->trans('geny.type.form.title.default', [], 'geny'),
               'label' => 'geny.type.form.title.label',
               'required' => true,
           ])
           ->add('description', Type\TextareaType::class, [
               'attr' => [
                   'placeholder' => 'geny.type.form.description.placeholder',
               ],
               'empty_data' => null,
               'label' => 'geny.type.form.description.label',
               'required' => false,
           ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => 'GenyBundle\Entity\Form',
            'translation_domain' => 'geny',
        ]);
    }
}

SubmitBuilderType.php

<?php

namespace GenyBundle\Form\Type;

use GenyBundle\Base\BaseType;
use Symfony\Component\Form\Extension\Core\Type;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class SubmitBuilderType extends BaseType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
           ->add('submit', Type\TextType::class, [
               'attr' => [
                   'placeholder' => 'geny.type.submit.submit.placeholder',
               ],
               'empty_data' => $this->get('translator')->trans('geny.type.submit.submit.default', [], 'geny'),
               'label' => 'geny.type.submit.submit.label',
               'required' => true,
           ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => 'GenyBundle\Entity\Form',
            'translation_domain' => 'geny',
        ]);
    }
}

Form.php

<?php

namespace GenyBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as Serializer;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Table(name="geny_form")
 * @ORM\Entity(repositoryClass="GenyBundle\Repository\FormRepository")
 * @ORM\ChangeTrackingPolicy("DEFERRED_EXPLICIT")
 * @Serializer\ExclusionPolicy("NONE")
 */
class Form
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Id
     * @Serializer\Exclude
     */
    protected $id;

    /**
     * @var string
     *
     * @ORM\Column(name="title", type="string", length=128)
     * @Assert\Length(min = 1, max = 128)
     * @Serializer\Type("string")
     */
    protected $title;

    /**
     * @var string
     *
     * @ORM\Column(name="description", type="text", nullable=true)
     * @Assert\Length(min = 0, max = 4096)
     * @Serializer\Type("string")
     */
    protected $description;

    /**
     * @var ArrayCollection
     *
     * @ORM\OneToMany(targetEntity="Field", mappedBy="form", cascade={"all"}, orphanRemoval=true)
     * @ORM\OrderBy({"position" = "ASC"})
     * @Assert\Valid()
     * @Serializer\Type("ArrayCollection<GenyBundle\Entity\Field>")
     */
    protected $fields;

    /**
     * @var string
     *
     * @ORM\Column(name="submit", type="text")
     * @Assert\Length(min = 1, max = 64)
     * @Serializer\Type("string")
     */
    protected $submit;
}

Result:

result

Alain Tiemblo
  • 36,099
  • 17
  • 121
  • 153