[英]<select> in Symfony2 Forms
我有兩張桌子
user
-------------------
id | name | city_id
-------------------
1 | abc | 1
2 | xyz | 3
3 | hkj | 3
-------------------
和
city
---------
id | name
---------
1 | BN
2 | KR
3 | OP
4 | HD
我正在使用Symfony2表單創建表單。 我想知道如何將所有城市列為<select>
表單元素的<option>
,以便為用戶xyz
生成以下標記。
<select>
<option>BN</option>
<option>KR</option>
<option selected='selected'>OP</option>
<option>HD</option>
</select>
目前,我的控制器中有類似這樣的代碼,
$user = // object of user entity
$form = $this->createFormBuilder($user)
->add('name', 'text')
->add('city', ...) // What do I put in here so that I generate the markup as specified above
->getForm();
您可以在此處查看: http : //symfony.com/doc/2.0/reference/forms/types/entity.html進行如下編碼:
->add('city', 'entity',
array('required' => true,
'label' => 'label',
'class' => 'YourBundle:TheClass',
'query_builder' => function(YourClassRepository $er) {
return $er->createQueryBuilder('e')->orderBy('e.name', 'ASC');
}
))
您只需要指定“屬性”字段即可。
->add('city', 'entity',
array('required' => true,
'label' => 'label',
'class' => 'YourBundle:TheClass',
'property' => 'name'
))
如果您希望查詢構建器僅限於某些選擇,則適用Sandeepraju的答案。
了解更多: http : //symfony.com/doc/current/reference/forms/types/entity.html#property
如果city是一個實體,那么它可以很簡單-> add('city')。 如果要使用默認值,則可以在$ options中提供實體,例如'data'=> $ defaultEntity。 另外,您的城市實體還必須具有__toString方法。 但是,如果您在城市上沒有實體,則可以使用類似的方法
$builder->add('gender', 'choice', array(
'choices' => array('m' => 'Male', 'f' => 'Female'),
'required' => false,
));
此字段可以呈現為幾個不同的HTML字段之一,具體取決於展開的選項和多個選項:
- 元素類型-(展開/多個)
- 選擇標簽-(false / false)
- 選擇標記多個-(false / true)
- 單選按鈕-(true / false)
- 復選框-(true / true)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.