Reputation: 2671
I have a issue with choices and formtype. Short description of my problem :
I have formtype with field that has choices
->add('fieldName2', 'choice', array(
'label' => 'Some label',
'choices' => array(
0 => 'Option 1',
1 => 'Option 2',
...,
n => 'Option n'
),
))
In database that field is int (must be a number). Now comes the problem : I want to list all the records for that table. Result is like :
fieldName1|fieldName2
----------|----------
somevalue | 0
somevalue | 1
somevalue | 2
but I wont to look like this:
fieldName1|fieldName2
----------|----------
somevalue | Option 1
somevalue | Option 2
somevalue | Option 3
How to combine formtype field choices and actual values in template. Do I have to create custom twig function for that or there is a built in solution?
Upvotes: 1
Views: 2012
Reputation: 36954
Assuming $data
contains your fields from a database in a controller, create the "choices" array:
$choices = array();
foreach ($data as $elem)
{
$choices[$elem] = "Option {$elem}";
}
Then, create your form and pass your choices array in constructor.
$form = $this->createForm(new YourFormType($choices), new YourFormData());
In your form, add a constructor:
private $choices;
// (...)
public function __construct(array $choices)
{
$this->choices = $choices;
}
Finally, create your field with your previously prepared array of choices.
(...)
->add('fieldName2', 'choice', array(
'label' => 'Some label',
'choices' => $this->choices,
))
Note: replace the property name "choices" by a less confusing name; will be easier to read if you have several choices that looks like this.
Upvotes: 2