Search code examples
symfonyformbuilder

Form Builder call in a form a form collection without "direct liaison"


In a form Demand, I want to create an Article, but Article and Demand are not directly joined tables, so how can I do that?

My Database conception:

| demand   |  1,n       |  listing |  n,n | article |

(Sorry, I can upload an image)

I'm lost; should I call a service or something?
I'd like to follow best practice in doing this.


Solution

  • I have found a solution. For make that i have simply call form to create Article and Demand, from the form for create listing.

    Like that

    <?php
    
    namespace OrderIT\Bundle\OrderBundle\Form;
    
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\FormBuilderInterface;
    use Symfony\Component\OptionsResolver\OptionsResolverInterface;
    
    class ListingType extends AbstractType
    {
        /**
         * @param FormBuilderInterface $builder
         * @param array $options
         */
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('demandDemand', new DemandType())
                ->add('articleArticle', 'collection', array(
                   'type' => new ArticleType(),
                   'allow_add' => true,
                   'by_reference' => false,))
            ;
        }
    
        /**
         * @param OptionsResolverInterface $resolver
         */
        public function setDefaultOptions(OptionsResolverInterface $resolver)
        {
            $resolver->setDefaults(array(
                'data_class' => 'OrderIT\Bundle\OrderBundle\Entity\Listing'
            ));
        }
    
        /**
         * @return string
         */
        public function getName()
        {
            return 'orderit_bundle_orderbundle_listing';
        }
    }