Post

Symfony – Afficher un formulaire Twig

Symfony – Afficher un formulaire Twig

Cours 21 — Afficher un formulaire Twig

Introduction

Une fois le formulaire créé dans le contrôleur, il doit être affiché dans une vue Twig.

Symfony fournit plusieurs fonctions pour afficher facilement les champs.


Contrôleur

1
2
3
return $this->render('patient/index.html.twig', [
    'form' => $form->createView()
]);

Afficher tout le formulaire

1
2
3
{{ form(form) }}

Symfony affiche automatiquement tous les champs.


Afficher le début et la fin du formulaire

1
2
3
4
5
{{ form_start(form) }}

{{ form_end(form) }}


Afficher un champ

1
2
3
{{ form_row(form.nom) }}

Résultat :

1
Label + Champ + Erreurs

Afficher séparément

1
2
3
4
5
6
7
{{ form_label(form.nom) }}

{{ form_widget(form.nom) }}

{{ form_errors(form.nom) }}


Exemple complet

1
2
3
4
5
6
7
8
9
10
11
12
13
{{ form_start(form) }}

{{ form_row(form.nom) }}

{{ form_row(form.prenom) }}

<button type="submit">
    Valider
</button>

{{ form_end(form) }}


Ajouter une classe Bootstrap

1
2
3
4
5
6
7
8
9
10
{{ form_widget(
    form.nom,
    {
        'attr': {
            'class': 'form-control'
        }
    }
) }}


Comprendre le processus

1
2
3
4
5
6
7
8
9
FormType
↓
Contrôleur
↓
createView()
↓
Twig
↓
Affichage HTML

Conclusion

Pour afficher un formulaire :

  • transmettre le formulaire à Twig ;
  • utiliser form_start() ;
  • afficher les champs ;
  • utiliser form_end().

Fonctions à retenir :

1
2
3
4
5
6
form_start()
form_end()
form_row()
form_label()
form_widget()
form_errors()
This post is licensed under CC BY 4.0 by the author.