Hewyn
Hewyn

Reputation: 175

symfony displaying my form as select tag

I am searching how to display all my attributes of my form that way:

For example in my entity class I have these attributes:

$number
$firstname
$lastname
$gender

And I want to display it like that instead of a classic form:

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

I searched if somebody already asked this and could not find anything.

Thanks for your help!

EDIT:

I am trying to do something like this:

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

Upvotes: 1

Views: 487

Answers (2)

pcm
pcm

Reputation: 856

It is, as you suggested, solvable with a choice entity field, however you need just a little bit more logic.
I am assuming you're building the form inside a Form Type.

$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
])

this snippet will result in a choice field containing all your entity fields in the choice list.
However this approach is a bit sloppy, and I'm sure you can find an architectural alternative in which you don't populate a choice field with your entity fields.. It smells like trouble to do so.

Anyway, if you need further help with this, please let me know!

Upvotes: 1

Alexandru Olaru
Alexandru Olaru

Reputation: 7092

From symfony 2 documentation you should use in the following mode:

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

Upvotes: 0

Related Questions