Symfony form select box: choosing default options from external data source

How do I populate a select option using an external dataset?

$builder->add('gender', 'choice', array(
    'choices' => [array from webservice or other class]
));

      

the documentation only shows a simple static array http://symfony.com/fr/doc/2.7/reference/forms/types/choice.html#choices

I tried:

:

$event = new Event();
$form = $this->createForm(new EventType($this->get('api')), $event);

      

:

class EventType extends AbstractType
{
    protected $myservice;

    public function __construct($myservice)
    {
        $this->myservice = $myservice;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('titre')
            ->add('id_rubrique', 'choice', array(
                'choices' => $this->myservice->getRubriques
        ;
    }

    ....
}

      

Correct solution?

+3


source to share


2 answers


Define form as a service:

services:
    my.form:
        class: EventType
        arguments:
            - @api

      



Then in the controller:

$event = new Event();
$form = $this->createForm('my.form', $event);

      

+2


source


Example

->add('education', 'choice', array('label' => 'Education *','choices' => $this->getEducation(), 'required' => true, 'empty_value' => 'select', 'empty_data'  => null))

      



$ this-> getEducation () is an array

// Array ('option1Value' => 'option1Name' ...

0


source







All Articles