Symfony: FormType, Entity, queryBuilder -如何更改生成选项的值


Symfony: FormType, Entity, queryBuilder - how change the value of generated options?

我想添加字段country (字符串)到我的Form'Type

countryEntity'Country无关,应存储国家代码(en, it, fr,…),而不是实体的ID。

我将Entity'Country的国家代码加载到我的表单中,但是生成的select将实体的ID作为值,__toString() -返回作为文本。

如何将c.code设置为<option>的值?

FormType:

public function buildForm(FormBuilderInterface $builder, array $options) {
    $builder->add('country', 'entity', array(
        'class' => 'appBundle:Country',
        'query_builder' => function (EntityRepository $er) {
            return $er->createQueryBuilder('c')->orderBy('c.code', 'ASC');
        }
    ));
}
选择生成

:

<select>
    <option value="1">en</option>
    <option value="2">it</option>
    <option value="3">fr</option>
</select>
所需选择

:

<select>
    <option value="en">en</option>
    <option value="it">it</option>
    <option value="fr">fr</option>
</select>

提前感谢!

如果您使用的是symfony 2.7,请使用entity表单字段类型的choice_label选项。如果使用旧版本的symfony,请使用property选项。更多信息请访问:http://symfony.com/doc/current/reference/forms/types/entity.html

public function buildForm(FormBuilderInterface $builder, array $options) {
    $builder->add('country', 'entity', array(
        'class' => 'appBundle:Country',
        'query_builder' => function (EntityRepository $er) {
            return $er->createQueryBuilder('c')->orderBy('c.code', 'ASC');
        },
        'choice_value'=>"country-code", //(country-code = column name in database)
        'choice_label'=>"country-name"
    ));
}