0

Is it possible to use collection in form type while calling a relationship field?

Here's what im trying to do:

I have a relationship between Candidates Entity & Districts Entity where a candidate can belong to multiple districts.

I set up the form type this way:

candidates type

$builder
    ->add('name')
    ->add('district', 'collection', array('type'=>new districtsChoiceType()))

districtschoice type

$builder
        ->add('candidate', 'entity', array(
                'class' => 'CMSElectionsBundle:districts',
                'query_builder' => function(EntityRepository $get) {
                    return $get->createQueryBuilder('p')->where('p.status = 1')->orderBy('p.id', 'ASC');
                }, 'property' => 'name', 'label' => ' '))

So im facing 2 problems here:

  1. when i want to create a new candidate, the district field appears empty/
  2. when i try to edit an existing candidate, i get the following error:

    Expected argument of type "array or (\Traversable and \ArrayAccess)", "Proxies\__CG__\CMS\ElectionsBundle\Entity\districts" given
    
j0k
  • 22,600
  • 28
  • 79
  • 90
Jean
  • 11
  • 3

1 Answers1

0

I would do this for the candidateType:

$builder            
    ->add('districts', 'entity', array(
                'label' => 'Districts',
                'class' => 'CMSElectionsBundle:District',
                'query_builder' => function(\CMS\ElectionsBundle\Entity\DistrictRepository $er) {
                    return $er->createQueryBuilder('a')
                        ;
                },
                'property' => 'choose one property from district',
                'expanded' => true,
                'multiple' => true,
                'required' => true,
            ))

Could you show us the code you used to create the relationship in both entities?

banban
  • 72
  • 8