(and sorry for my English)
I am working on a Silex project and I start using the form.
Without form, i have something like this :
And using the form I would like to have the same thing ( for the select )
End with the form i have this :
As you can see the rendering is not great.
I would like to get a few things like:
<option value="1">Méthode</option>
<option value="2">Marketing</option>
<option value="3">Production</option>
At the code level, I have something very simple ( I start on the forms, be indulgent haha) : Controller :
public function add(Application $app, Request $request) {
if (! $app['security.authorization_checker']->isGranted('ROLE_ADMIN')) {
return new Response('Access Denied!', 403);
}
$repo = new DepartementRepository($app);
$departements = $repo->getAllDepartements();
$data = [];
$erreurs = [];
$form = $app['form.factory']->createBuilder(FormType::class, $data)
->add('nom',null,array('label' => 'Nom :'))
->add('prenom',null,array('label' => 'Prenom :'))
->add('departement_id',ChoiceType::class,array('choices' => $departements,'label' => 'Departement :'))
->add('ville',null,array('label' => 'Ville :'))
->add('salaire',null,array('label' => 'Salaire :'))
->add('date_embauche',null,array('label' => 'Date d\'embauche :'))
->getForm();
$form->handleRequest($request);
if ($form->isValid())
{
$data = $form->getData();
}
return $app['twig']->render('employe/new.html.twig', array('form' => $form->createView(),'erreurs'=> $erreurs));
}
if i dump my $departements variable, i have this :
array:4 [▼
0 => array:2 [▼
"id" => "2"
"nom_dep" => "Marketing"
]
1 => array:2 [▼
"id" => "3"
"nom_dep" => "Méthode"
]
2 => array:2 [▼
"id" => "1"
"nom_dep" => "Production"
]
3 => array:2 [▼
"id" => "4"
"nom_dep" => "Recherche et developpement"
]
]
And my view :
<form action="#" method="post">
{{ form_widget(form) }}
<input type="submit" name="submit" />
</form>
Before I did that:
{% for departement in departements %}
<option value="{{ departement.id }}"
{% if donnees.departement_id is defined and departement.id == donnees.departement_id %}selected{% endif %}>
{{ departement.nom_dep }}
</option>
{% endfor %}
But I do not know how to do this with the form.
Any help is welcome. Thanks !!
ChoiceType takes an array as parameter:
Array style (like your current repo)
$departements = $repo->getAllDepartements();
$departementChoices = [];
foreach( $departements as $departement) {
$departementChoices[$departement["id"]] = $departement["nom_dep"]
}
Object style
$departements = $repo->getAllDepartements();
$departementChoices = [];
foreach( $departements as $departement) {
$departementChoices[$departement->getId()] = $departement->getLabel()
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.