Symfony2 Forms - Selected Value in Dropdown using Propel ModelType

梦想与她 提交于 2019-12-06 06:35:38

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!