symfony将我的表单显示为选择标记

时间:2015-04-09 10:51:57

标签: php symfony doctrine twig

我正在搜索如何以这种方式显示我的表单的所有属性:

例如,在我的实体类中,我有以下属性:

$number
$firstname
$lastname
$gender

我希望像那样展示它而不是经典形式:

<select>
  <option value='number'>customized name</option>
  <option value='firstname'>customized name</option>
  <option value='lastname'>customized name</option>
  <option value='gender'>customized name</option>
</select>
<input type="text" name="text"/>
<input type="submit" value="Submit"/>

我搜索了是否有人已经问过这个并且找不到任何东西。

感谢您的帮助!

编辑:

我正在尝试做这样的事情:

$builder
            ->add('choices' => array('number' => 'Personel Number',
                                    'firstname' => 'First Name',
                                    'lastname' => 'Last Name',)
                'required' => true,
            ))
            ->add('Search',             'submit')

2 个答案:

答案 0 :(得分:1)

正如你所建议的那样,它可以用一个选择实体字段来解决,但是你需要更多的逻辑。
我假设您正在表单类型中构建表单

$choiceKeys = array_keys($options['data']); // where $options['data'] is your entity object! The form type automatically sets this variable
foreach ($choiceKeys as $key) {
    $choiceList[$key] = $some_translator->trans($key); // this should be the easiest way to get your fields translated like you want.
}

$builder->add('fieldName', 'choice', [
  'choices' => $choiceList
])

此代码段将生成一个包含所选实体列表中所有实体字段的选项字段 然而,这种方法有点草率,我相信你可以找到一个架构替代方案,你不用实体字段填充选择字段。这样做有点麻烦。

无论如何,如果您需要进一步的帮助,请告诉我!

答案 1 :(得分:0)

从symfony 2文档中,您应该使用以下模式:

$builder->add('foo_choices', 'choice', array(
     'choices' => array('foo' => 'Foo', 'bar' => 'Bar', 'baz' => 'Baz'),
     'preferred_choices' => array('baz'),
));
相关问题