Templating, Forms
Returning Views, using Twig, submitting forms
Table of Contents
1. Templating
2. Forms
2
TEMPLATING
Templates and Twig
Templating
• In Symfony you can use two type of templates
– php - standard html + php code in our templates
– twig - flexible template language
4
Templating
• Templates Location
– per application - templates can be accessed from any bundle
– per bundle - templates can be accessed from any bundle
• using the namespace notation
Templating
• Templating language
• Easier to read
• Creates much cleaner templates
• Combines iteration with condition
• Allows inheritance between templates
• Automatic escaping and raw output
• Extensions
Templating
• Twig and Controllers
– pass parameters to template
– $this->render() - render template and create Response object
– $this->renderView() - render
Templating
• Twig
{{ … }} - print variable or text
{% ... %} - used for logic blocks
{# … #} - twig comment
Templating
• What can we do with Twig?
– extend template
– combine conditional statements and loops
– access object property with dot notation
– generate links
– override blocks, create macros, extend parent block
– include another template
– include assets
– create custom twig extensions
Templating
• What can we do with Twig?
– app.user - get current user
– app.request - get current request
– app.session - get session
– app.environment - get application environment
– app.debug - check debug status of the application
– access global twig variable - can create global twig
variables and access them in your templates
FORMS
Forms and Templates
Forms
• Form flow:
– create the form
– set the data
– handle request
– do something with submitted data
– save to database
– remove from database
– update database
Forms
• Form flow
Forms
• Two ways to create forms in Symfony
– in your controller action using the form builder
Forms
• Two ways to create forms in Symfony
– using separate form class
Forms
• A form should know what input field to render
– TextType - input type="text"
– SubmitType - input type="submit"
– ChoiceType - generates select, checkboxes or radio
buttons
– HiddenType - input type="hidden"
– RepeatedType - used to render input fields for
passwords and confirmation
Forms
• To display form in template it must be passed as view
parameter
EXAMPLE
Folder Structure
Note.php
NoteFormType.php
NoteController.php
SuccessController.php
base.html.twig
templates/note/index.html.twig
templates/success/index.html.twig
Result
Summary
• Templating
• Twig, extending templates, blocks
• Twig extensions, macros
• Forms
• Rest concepts, REST URIs, Responses
28