I’m building a form which contains a category field. I need a choice list to do that, but I don’t find out how to fill this choice list with the several categories stored in the database.
public function buildForm(FormBuilder $builder, array $options) {
$builder->add('item', 'text', array('label' => 'Item'));
$builder->add('category', 'choice', array(
'choices' => ???,
'label' => 'Category'
));
}
How can I get the categories from the database?
(I can’t seem to access $this->getDoctrine() inside this class.)
Use type
entityinstead ofchoiceEdit:
Two ways for using custom parameters in your query. In both situations, the parameters are injected from outside, so your FormType don’t need any references to the session or request objects or whatever.
1- Pass required parameters to your constructor
in your
buildForm()you must copy the value to local variable and make it available for the query_builder callback:2- use the
$optionsparameter of thebuildFormmethod.First you have to define a default value by overriding
getDefaultOptions:Then you can pass it from your controller in the third argument of the
createFormmethod.Now the value should be available through the
$optionsparameter of youru buildForm method. Pass it to the callback as described above.