jacobmaster
jacobmaster

Reputation: 770

Symfony2 - form entity field with multiple , data not preserved after choices set

I'm using form to edit some data. one of the form field:

$builder ->add('cities', 'entity', array(
    'class'    => 'Vendor\SomeBundle\Entity\City',
    'multiple' => true
));

everthing works fine - i have some preselected cities in accordance with the database.

Now i want to limit choices to cities form specific country. So I get collection of cities and set 'choices' option:

$builder ->add('cities', 'entity', array(
    'class'    => 'Vendor\SomeBundle\Entity\City',
    'multiple' => true,
    'choices'  => $citiesCollection
));

The choice list is limited but no cities are selected.

i try to set this preselected cities using 'data' option but this also does not work

$builder ->add('cities', 'entity', array(
    'class' => 'Vendor\SomeBundle\Entity\City',
    'multiple' => true,
    'choices'  => $citiesCollection
    'data'     => $citiesSelected
));

trying different approaches, passing ArrayCollection, array, array of keys but nothing works... It is even possible?

Upvotes: 0

Views: 697

Answers (2)

jacobmaster
jacobmaster

Reputation: 770

The working solution - set 'query_builder" option instead of 'choices'

$builder ->add('cities', 'entity', array(
    'class'    => 'Vendor\SomeBundle\Entity\City',
    'multiple' => true,
    'query_builder'  => $citiesQueryBuilder
));

now rendered form has selected cities

Upvotes: 1

dbonfill
dbonfill

Reputation: 34

I think that assigning the $citiesSelected array to the cities field of the base entity assigned to the form will make the trick.

Upvotes: -1

Related Questions