2013-04-23 42 views
0

我有两个表,<select>在Symfony2的窗体

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的形式形式。我想知道如何列出所有城市为<option><select>表单元素,以便为用户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(); 

回答

1

你可以看看有: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'); 
       } 
)) 
1

如果城市是一个实体,比它可以是简单的 - >添加( '城市')。如果你想要一个默认值,你可以在$ options中提供实体,比如'data'=> $ defaultEntity。你的城市实体也必须有一个__toString方法。 但是,如果你没有在城市的实体,您可以使用类似的东西

$builder->add('gender', 'choice', array(
    'choices' => array('m' => 'Male', 'f' => 'Female'), 
    'required' => false, 
)); 

该字段可以被渲染为几个不同的HTML的领域之一,这取决于扩大和多种选择:

  • 元件类型 - (膨胀/多个)
  • 选择标签 - (假/假)
  • 选择标签多重(假/真)
  • 无线电buttons-(真/假)
  • checkboxes-(真/真)