【问题标题】:<select> in Symfony2 FormsSymfony2 表单中的 <select>
【发布时间】:2013-04-23 13:45:58
【问题描述】:

我有两张桌子,

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 表单创建一个表单。我想知道如何将所有城市列为&lt;option&gt;&lt;select&gt; 表单元素,以便为用户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();

【问题讨论】:

    标签: php forms symfony symfony-forms


    【解决方案1】:

    您只需要指定“属性”字段。

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

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

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

        此字段可能会呈现为几个不同的 HTML 字段之一,具体取决于扩展选项和多个选项:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-08-14
          • 2012-02-09
          • 1970-01-01
          • 2017-02-14
          • 1970-01-01
          • 2011-09-20
          • 2023-03-07
          • 1970-01-01
          相关资源
          最近更新 更多