<select> in Symfony2 Forms


<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();

您只需要指定'property'字段。

->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

您可以在那里查看: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');
                }
 ))

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

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

该字段可能被呈现为几个不同的HTML字段之一,取决于展开和多个选项:

  • 元素类型(扩展/多个)
  • 选择标签(假/假)
  • select tag multiple-(false/true)
  • 单选按钮(真/假)
  • 复选框(真/真)