You can pass the selection to your form using ..
$chooseRouteForm = $this->createForm(new ChooseRouteForm($routeSetup), $routeSetup);
Then in your form ..
private $countries; public function __construct(RouteSetup $routeSetup) { $this->countries = $routeSetup->getCountries(); } public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('countries', 'choice', array( 'choices' => $this->countries, )); }
Updated (and improved) for 2.8+
Firstly, you do not need to go through countries as part of the route object if they are not stored in the database.
If you save the available countries in the database, you can use the event listener. If not (or if you do not want to use a listener), you can add countries to the options area.
Using options
In the controller ..
$chooseRouteForm = $this->createForm( ChooseRouteForm::class, // Or the full class name if using < php 5.5 $routeSetup, array('countries' => $fields->getCountries()) );
And in your form ..
public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('countries', 'choice', array( 'choices' => $options['countries'], )); } public function configureOptions(OptionsResolver $resolver) { $resolver ->setDefault('countries', null) ->setRequired('countries') ->setAllowedTypes('countries', array('array')) ; }
Using a listener (If an array of models is available in the model)
In the controller ..
$chooseRouteForm = $this->createForm( ChooseRouteForm::class, // Or the full class name if using < php 5.5 $routeSetup );
And in your form ..
public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event) { $form = $event->getForm(); $routeSetup = $event->getData(); if (null === $routeSetup) { throw new \Exception('RouteSetup must be injected into form'); } $form ->add('countries', 'choice', array( 'choices' => $routeSetup->getCountries(), )) ; }) ; }