Mr. B. Mr. B. - 8 days ago 5
PHP Question

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

I'd like to add the field

country
(string) to my
Form\Type
.

country
is not related to
Entity\Country
, and should store country-codes (en, it, fr, ...) instead of the entity's ID.

I load the country codes of
Entity\Country
to my form, but the generated select has the entity's ID as the value, the
__toString()
-return as text.

How can I set
c.code
as the
<option>
s value?

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');
}
));
}


Generated select:

<select>
<option value="1">en</option>
<option value="2">it</option>
<option value="3">fr</option>
</select>


Desired select:

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


Thanks in advance!

Answer

If you are using symfony 2.7, use the choice_label option of the entity form field type. If using an older version of symfony, use the property option. More information here: http://symfony.com/doc/current/reference/forms/types/entity.html