问题
I'm trying to set the selected value of a 'model' (ModelType from the Symfony Propel Bridge) form type and I'm failing miserably.
There is Product table with the following structure:
id, name, category_id
Example data would be:
id => 1, name => 'Test', category_id => 3
Another table holds the Category data, so category_id is a foreign key.
id => 1, name => 'Category 1'
id => 2, name => 'Category 2'
id => 3, name => 'Category 3'
The form type I'm working with is:
$builder->add('category_id', 'model', array(
'class' => 'Foo\BarBundle\Model\Category',
'required' => true,
'multiple' => false,
'expanded' => false,
'label' => 'Pick a product category!',
'query' => CategoryQuery::create()->orderByName(),
));
Now when I load up the form, I get a nice select drop-down containing the ordered Categories as you would expect.
What I'd like the drop-down to do is display the correct "selected" Category for a Product that already exists (use case: in a Product Edit form). So, Product ID 1 would have a selected option of "Category 3".
I tried setting a "data" option (which was ignored) so I'm perplexed as to why something so fundamental seems so difficult.
Any help would be greatly appreciated.
UPDATE: Problem solved, see below:
$builder->add('category', 'model', array(
'class' => 'Foo\BarBundle\Model\Category',
'required' => true,
'multiple' => false,
'expanded' => false,
'label' => 'Pick a product category!',
'query' => CategoryQuery::create()->orderByName(),
));
Changed 'category_id' to 'category' and everything was right with the world once more.
来源:https://stackoverflow.com/questions/14394825/symfony2-forms-selected-value-in-dropdown-using-propel-modeltype