Salim Ben Aissa
Salim Ben Aissa

Reputation: 465

Symfony 3.4 ChoiceType dynamically add choices

I need your help with a little issue with Symfony 3.4 forms.

The idea is that I have a Data entity which assigned to a Trip entity (the Trip table is the parent of the Data table which has a column trip_id references Trip.id). And of course trips are submitted with a form and saved in the database.

But when I want to add a data I want also to added the trip_id. I tried this because I found it logical but it seems at the end that its just an illusion:

$formBuilder->add('trip', ChoiceType::class, [
            'choices' => [
                foreach ($trips in trip){
                    "$trip->getName()" => "$trip->getId()"
                }
            ]
        ])

I think you got the idea. I want to retrieve the trips from the database and dynamically add them to the ChoiceType, exactly like we do in a normal PHP:

<form action="#" method..>
    <select>
       <?php foreach ($trips as $trip){
       '<option value='".$trip->getId().'">'.$trip->getName().'</option>
       }?>
    </select>
</form>

Upvotes: 1

Views: 2644

Answers (1)

Pec
Pec

Reputation: 106

You need an EntityType field for that

https://symfony.com/doc/current/reference/forms/types/entity.html

Upvotes: 1

Related Questions