SlideShare uma empresa Scribd logo
1 de 26
Baixar para ler offline
Symfony2
Form and Validation
Creating an Entity Class
// src/Volcano/VideostatusBundle/Entity/Clip.php
namespace VolcanoVideostatusBundleEntity;
class Clip
{
protected $id;
protected $url;
protected $timeStart;
protected $timeFinish;
}
Creating a Simple Form:
Controller
class DefaultController extends Controller
{
public function newAction(Request $request)
{
$clip = new Clip();
//...
$form = $this->createFormBuilder($clip)
->add('url', 'text')
->add('timeStart', 'integer')
->add('timeFinish', 'integer')
->add('save', 'submit')
->getForm();
return $this->render('VolcanoideasVideoBundle:Default:new.html.twig', array(
'form' => $form->createView(),
));
}
}
Creating a Simple Form:
Template
{% extends "AcmeDemoBundle::layout.html.twig" %}
{% block content %}
<h1 class="title">Form demo</h1>
{{ form(form) }}
{% endblock %}
Creating a Simple Form:
Template
Creating a Simple Form:
Controller
class DefaultController extends Controller
{
public function newAction(Request $request)
{
$clip = new Clip();
$form = $this->createFormBuilder($clip)
//...
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
// perform some action, such as saving the task to the database
return $this->redirect($this->generateUrl('clip_success'));
}
//
}
}
Validation
use SymfonyComponentValidatorConstraints as Assert;
class Clip
{
/**
* @AssertNotBlank(message="Enter URL")
* @AssertUrl(message="Enter valid URL", protocols={"http", "https"})
*/
protected $url;
/**
* @AssertNotBlank(message="Enter Start Time")
* @AssertType(type="integer")
*/
protected $timeStart;
}
Validation service
$clip = new Clip();
//...
$validator = $this->get('validator');
$errors = $validator->validate($clip);
if (count($errors) > 0) {
return new Response(print_r($errors, true));
} else {
return new Response('The clip is valid!');
}
Creating Form Classes
// src/Volcano/VideoBundle/Form/Type/ClipType.php
namespace VolcanoVideoBundleFormType;
use SymfonyComponentFormAbstractType;
use SymfonyComponentFormFormBuilderInterface;
class ClipType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('url','text');
$builder->add('timeStart', 'integer');
//...
}
public function getName()
{
return 'task';
}
}
Creating a Simple Form:
Controller
class DefaultController extends Controller
{
public function newAction(Request $request)
{
$clip = new Clip();
$form = $this->createForm(new ClipType(), $clip);
$form->handleRequest($request);
if ($form->isValid()) {
// perform some action, such as saving the task to the database
return $this->redirect($this->generateUrl('clip_success'));
}
//
}
}
Creating Form Classes
// src/Volcano/VideoBundle/Form/Type/ClipType.php
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'VolcanoVideoBundleEntityClip',
));
}
Creating a Simple Form:
Template
{% extends "AcmeDemoBundle::layout.html.twig" %}
{% block content %}
<h1 class="title">Form demo</h1>
{{ form(form) }}
{% endblock %}
Creating a Simple Form:
Template
Creating a Simple Form:
Template
<form method="post" action="">
<div id="form">
<div>
<label for="form_url" class="required">Url</label>
<input type="text" id="form_url" name="form[url]" required="required">
</div>
<div>...</div>
<div>
<button type="submit" id="form_save" name="form[save]">Save</button>
</div>
<input type="hidden" id="form__token" name="form[_token]" value="
f9fa3d38371a9344a906049a1ab0bdda5f5374a3">
</div>
</form>
Rendering a Form
{{ form_start(form) }}
{{ form_errors(form) }}
{{ form_row(form.url) }}
{{ form_row(form.timeStart) }}
{{ form_row(form.timeFinish) }}
{{ form_row(form.save) }}
{{ form_end(form) }}
Rendering a Form:
form_row
{{ form_label(form.url) }}
{{ form_errors(form.url) }}
{{ form_widget(form.url) }}
Rendering a Form:
form_label
{{ form_label(form.url, "Clip URL") }}
<label for="form_url" class="required">Clip URL</label>
Rendering a Form:
form_errors
{{ form_errors(form.url) }}
<ul><li>This value is not a valid URL.</li></ul>
Rendering a Form:
form_widget
{{ form_widget(form.url, {'attr': {'class': 'text-input'}}) }}
<input type="text" id="form_url" class="text-input" name="form[url]" required="required"
value="123123">
Form theming:
Inside a Separate Template
{# src/Volcano/VideoBundle/Resources/views/Form/fields.html.twig #}
{% block form_row %}
{% spaceless %}
<div class="form_row">
{{ form_label(form) }}
{{ form_errors(form) }}
{{ form_widget(form) }}
</div>
{% endspaceless %}
{% endblock form_row %}
Form theming:
Inside a Separate Template
{% form_theme form 'VolcanoVideoBundle:Form:fields.html.twig' %}
{% block content %}
{{ form(form) }}
{% endblock content %}
Form theming:
Inside the same Template
{% form_theme form _self %}
{% block content %}
{{ form(form) }}
{% endblock content %}
{% block form_row %}
{% spaceless %}
<div class="form_row">
{{ form_label(form) }}
{{ form_errors(form) }}
{{ form_widget(form) }}
</div>
{% endspaceless %}
{% endblock form_row %}
Form theming:
Global
# app/config/config.yml
twig:
form:
resources:
- 'VolcanoVideoBundle:Form:fields.html.twig'
Form theming:
Individual field
{% form_theme form _self %}
{% block _form_url_row %}
<div class="url">
{{ form_label(form) }}
{{ form_errors(form) }}
{{ form_widget(form) }}
</div>
{% endblock %}
Embedding a Collection of
Forms
// src/Volcano/VideoBundle/Form/Type/TagType.php
class TagType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name');
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'VolcanoVideostatusBundleEntityTag',
));
}
public function getName()
{
return 'tag';
}
}
Embedding a Collection of
Forms
// src/Volcano/VideoBundle/Form/Type/ClipType.php
class ClipType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('url','text');
$builder->add('timeStart', 'integer');
//...
$builder->add('tags', 'collection', array(
'type' => new TagType(),
'allow_add' => true,
'allow_delete' => true
)
);
}
}

Mais conteúdo relacionado

Mais procurados

Advanced jQuery
Advanced jQueryAdvanced jQuery
Advanced jQuerysergioafp
 
Юрий Буянов «Squeryl — ORM с человеческим лицом»
Юрий Буянов «Squeryl — ORM с человеческим лицом»Юрий Буянов «Squeryl — ORM с человеческим лицом»
Юрий Буянов «Squeryl — ORM с человеческим лицом»e-Legion
 
JQuery In Rails
JQuery In RailsJQuery In Rails
JQuery In RailsLouie Zhao
 
Rails GUI Development with Ext JS
Rails GUI Development with Ext JSRails GUI Development with Ext JS
Rails GUI Development with Ext JSMartin Rehfeld
 
Write Less Do More
Write Less Do MoreWrite Less Do More
Write Less Do MoreRemy Sharp
 
Jquery In Rails
Jquery In RailsJquery In Rails
Jquery In Railsshen liu
 
Building Persona: federated and privacy-sensitive identity for the Web (Open ...
Building Persona: federated and privacy-sensitive identity for the Web (Open ...Building Persona: federated and privacy-sensitive identity for the Web (Open ...
Building Persona: federated and privacy-sensitive identity for the Web (Open ...Francois Marier
 
Polymer - pleasant client-side programming with web components
Polymer - pleasant client-side programming with web componentsPolymer - pleasant client-side programming with web components
Polymer - pleasant client-side programming with web componentspsstoev
 
Django class based views for beginners
Django class based views for beginnersDjango class based views for beginners
Django class based views for beginnersSpin Lai
 
How kris-writes-symfony-apps-london
How kris-writes-symfony-apps-londonHow kris-writes-symfony-apps-london
How kris-writes-symfony-apps-londonKris Wallsmith
 
Prototype & jQuery
Prototype & jQueryPrototype & jQuery
Prototype & jQueryRemy Sharp
 
HOW TO CREATE A MODULE IN ODOO
HOW TO CREATE A MODULE IN ODOOHOW TO CREATE A MODULE IN ODOO
HOW TO CREATE A MODULE IN ODOOCeline George
 
Xml operations in odoo
Xml operations in odooXml operations in odoo
Xml operations in odooCeline George
 
Open Selector
Open SelectorOpen Selector
Open Selectorjjdelc
 

Mais procurados (20)

Advanced jQuery
Advanced jQueryAdvanced jQuery
Advanced jQuery
 
jQuery Presentasion
jQuery PresentasionjQuery Presentasion
jQuery Presentasion
 
Introducing jQuery
Introducing jQueryIntroducing jQuery
Introducing jQuery
 
Юрий Буянов «Squeryl — ORM с человеческим лицом»
Юрий Буянов «Squeryl — ORM с человеческим лицом»Юрий Буянов «Squeryl — ORM с человеческим лицом»
Юрий Буянов «Squeryl — ORM с человеческим лицом»
 
J query training
J query trainingJ query training
J query training
 
JQuery In Rails
JQuery In RailsJQuery In Rails
JQuery In Rails
 
Rails GUI Development with Ext JS
Rails GUI Development with Ext JSRails GUI Development with Ext JS
Rails GUI Development with Ext JS
 
Write Less Do More
Write Less Do MoreWrite Less Do More
Write Less Do More
 
Jquery In Rails
Jquery In RailsJquery In Rails
Jquery In Rails
 
PhoneGap: Local Storage
PhoneGap: Local StoragePhoneGap: Local Storage
PhoneGap: Local Storage
 
Building Persona: federated and privacy-sensitive identity for the Web (Open ...
Building Persona: federated and privacy-sensitive identity for the Web (Open ...Building Persona: federated and privacy-sensitive identity for the Web (Open ...
Building Persona: federated and privacy-sensitive identity for the Web (Open ...
 
Polymer - pleasant client-side programming with web components
Polymer - pleasant client-side programming with web componentsPolymer - pleasant client-side programming with web components
Polymer - pleasant client-side programming with web components
 
Django class based views for beginners
Django class based views for beginnersDjango class based views for beginners
Django class based views for beginners
 
How kris-writes-symfony-apps-london
How kris-writes-symfony-apps-londonHow kris-writes-symfony-apps-london
How kris-writes-symfony-apps-london
 
Prototype & jQuery
Prototype & jQueryPrototype & jQuery
Prototype & jQuery
 
Matters of State
Matters of StateMatters of State
Matters of State
 
HOW TO CREATE A MODULE IN ODOO
HOW TO CREATE A MODULE IN ODOOHOW TO CREATE A MODULE IN ODOO
HOW TO CREATE A MODULE IN ODOO
 
[ HackFest.pl 2012] Testing - what for and how
[ HackFest.pl 2012] Testing - what for and how[ HackFest.pl 2012] Testing - what for and how
[ HackFest.pl 2012] Testing - what for and how
 
Xml operations in odoo
Xml operations in odooXml operations in odoo
Xml operations in odoo
 
Open Selector
Open SelectorOpen Selector
Open Selector
 

Semelhante a Symfony2. Form and Validation

Symfony CoP: Form component
Symfony CoP: Form componentSymfony CoP: Form component
Symfony CoP: Form componentSamuel ROZE
 
Apostrophe
ApostropheApostrophe
Apostrophetompunk
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Fabien Potencier
 
Михаил Крайнюк - Form API + Drupal 8: Form and AJAX
Михаил Крайнюк - Form API + Drupal 8: Form and AJAXМихаил Крайнюк - Form API + Drupal 8: Form and AJAX
Михаил Крайнюк - Form API + Drupal 8: Form and AJAXDrupalSib
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologyDaniel Knell
 
Taming forms with React
Taming forms with ReactTaming forms with React
Taming forms with ReactGreeceJS
 
Mashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web AppsMashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web AppsBastian Hofmann
 
A multi submission importer for easyform
A multi submission importer for easyformA multi submission importer for easyform
A multi submission importer for easyformAnnette Lewis
 
카카오커머스를 지탱하는 Angular
카카오커머스를 지탱하는 Angular카카오커머스를 지탱하는 Angular
카카오커머스를 지탱하는 Angularif kakao
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsMichael Peacock
 
Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)tompunk
 
Form demoinplaywithmysql
Form demoinplaywithmysqlForm demoinplaywithmysql
Form demoinplaywithmysqlKnoldus Inc.
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutesBarang CK
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 MinutesAzim Kurt
 

Semelhante a Symfony2. Form and Validation (20)

Symfony CoP: Form component
Symfony CoP: Form componentSymfony CoP: Form component
Symfony CoP: Form component
 
Apostrophe
ApostropheApostrophe
Apostrophe
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
 
Михаил Крайнюк - Form API + Drupal 8: Form and AJAX
Михаил Крайнюк - Form API + Drupal 8: Form and AJAXМихаил Крайнюк - Form API + Drupal 8: Form and AJAX
Михаил Крайнюк - Form API + Drupal 8: Form and AJAX
 
Migrare da symfony 1 a Symfony2
 Migrare da symfony 1 a Symfony2  Migrare da symfony 1 a Symfony2
Migrare da symfony 1 a Symfony2
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
Taming forms with React
Taming forms with ReactTaming forms with React
Taming forms with React
 
Mashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web AppsMashing up JavaScript – Advanced Techniques for modern Web Apps
Mashing up JavaScript – Advanced Techniques for modern Web Apps
 
Mashing up JavaScript
Mashing up JavaScriptMashing up JavaScript
Mashing up JavaScript
 
A multi submission importer for easyform
A multi submission importer for easyformA multi submission importer for easyform
A multi submission importer for easyform
 
카카오커머스를 지탱하는 Angular
카카오커머스를 지탱하는 Angular카카오커머스를 지탱하는 Angular
카카오커머스를 지탱하는 Angular
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friends
 
CakePHP workshop
CakePHP workshopCakePHP workshop
CakePHP workshop
 
Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)
 
Form demoinplaywithmysql
Form demoinplaywithmysqlForm demoinplaywithmysql
Form demoinplaywithmysql
 
Django quickstart
Django quickstartDjango quickstart
Django quickstart
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 
Django Bogotá. CBV
Django Bogotá. CBVDjango Bogotá. CBV
Django Bogotá. CBV
 

Último

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 

Último (20)

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 

Symfony2. Form and Validation

  • 2. Creating an Entity Class // src/Volcano/VideostatusBundle/Entity/Clip.php namespace VolcanoVideostatusBundleEntity; class Clip { protected $id; protected $url; protected $timeStart; protected $timeFinish; }
  • 3. Creating a Simple Form: Controller class DefaultController extends Controller { public function newAction(Request $request) { $clip = new Clip(); //... $form = $this->createFormBuilder($clip) ->add('url', 'text') ->add('timeStart', 'integer') ->add('timeFinish', 'integer') ->add('save', 'submit') ->getForm(); return $this->render('VolcanoideasVideoBundle:Default:new.html.twig', array( 'form' => $form->createView(), )); } }
  • 4. Creating a Simple Form: Template {% extends "AcmeDemoBundle::layout.html.twig" %} {% block content %} <h1 class="title">Form demo</h1> {{ form(form) }} {% endblock %}
  • 5. Creating a Simple Form: Template
  • 6. Creating a Simple Form: Controller class DefaultController extends Controller { public function newAction(Request $request) { $clip = new Clip(); $form = $this->createFormBuilder($clip) //... ->getForm(); $form->handleRequest($request); if ($form->isValid()) { // perform some action, such as saving the task to the database return $this->redirect($this->generateUrl('clip_success')); } // } }
  • 7. Validation use SymfonyComponentValidatorConstraints as Assert; class Clip { /** * @AssertNotBlank(message="Enter URL") * @AssertUrl(message="Enter valid URL", protocols={"http", "https"}) */ protected $url; /** * @AssertNotBlank(message="Enter Start Time") * @AssertType(type="integer") */ protected $timeStart; }
  • 8. Validation service $clip = new Clip(); //... $validator = $this->get('validator'); $errors = $validator->validate($clip); if (count($errors) > 0) { return new Response(print_r($errors, true)); } else { return new Response('The clip is valid!'); }
  • 9. Creating Form Classes // src/Volcano/VideoBundle/Form/Type/ClipType.php namespace VolcanoVideoBundleFormType; use SymfonyComponentFormAbstractType; use SymfonyComponentFormFormBuilderInterface; class ClipType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('url','text'); $builder->add('timeStart', 'integer'); //... } public function getName() { return 'task'; } }
  • 10. Creating a Simple Form: Controller class DefaultController extends Controller { public function newAction(Request $request) { $clip = new Clip(); $form = $this->createForm(new ClipType(), $clip); $form->handleRequest($request); if ($form->isValid()) { // perform some action, such as saving the task to the database return $this->redirect($this->generateUrl('clip_success')); } // } }
  • 11. Creating Form Classes // src/Volcano/VideoBundle/Form/Type/ClipType.php public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'VolcanoVideoBundleEntityClip', )); }
  • 12. Creating a Simple Form: Template {% extends "AcmeDemoBundle::layout.html.twig" %} {% block content %} <h1 class="title">Form demo</h1> {{ form(form) }} {% endblock %}
  • 13. Creating a Simple Form: Template
  • 14. Creating a Simple Form: Template <form method="post" action=""> <div id="form"> <div> <label for="form_url" class="required">Url</label> <input type="text" id="form_url" name="form[url]" required="required"> </div> <div>...</div> <div> <button type="submit" id="form_save" name="form[save]">Save</button> </div> <input type="hidden" id="form__token" name="form[_token]" value=" f9fa3d38371a9344a906049a1ab0bdda5f5374a3"> </div> </form>
  • 15. Rendering a Form {{ form_start(form) }} {{ form_errors(form) }} {{ form_row(form.url) }} {{ form_row(form.timeStart) }} {{ form_row(form.timeFinish) }} {{ form_row(form.save) }} {{ form_end(form) }}
  • 16. Rendering a Form: form_row {{ form_label(form.url) }} {{ form_errors(form.url) }} {{ form_widget(form.url) }}
  • 17. Rendering a Form: form_label {{ form_label(form.url, "Clip URL") }} <label for="form_url" class="required">Clip URL</label>
  • 18. Rendering a Form: form_errors {{ form_errors(form.url) }} <ul><li>This value is not a valid URL.</li></ul>
  • 19. Rendering a Form: form_widget {{ form_widget(form.url, {'attr': {'class': 'text-input'}}) }} <input type="text" id="form_url" class="text-input" name="form[url]" required="required" value="123123">
  • 20. Form theming: Inside a Separate Template {# src/Volcano/VideoBundle/Resources/views/Form/fields.html.twig #} {% block form_row %} {% spaceless %} <div class="form_row"> {{ form_label(form) }} {{ form_errors(form) }} {{ form_widget(form) }} </div> {% endspaceless %} {% endblock form_row %}
  • 21. Form theming: Inside a Separate Template {% form_theme form 'VolcanoVideoBundle:Form:fields.html.twig' %} {% block content %} {{ form(form) }} {% endblock content %}
  • 22. Form theming: Inside the same Template {% form_theme form _self %} {% block content %} {{ form(form) }} {% endblock content %} {% block form_row %} {% spaceless %} <div class="form_row"> {{ form_label(form) }} {{ form_errors(form) }} {{ form_widget(form) }} </div> {% endspaceless %} {% endblock form_row %}
  • 23. Form theming: Global # app/config/config.yml twig: form: resources: - 'VolcanoVideoBundle:Form:fields.html.twig'
  • 24. Form theming: Individual field {% form_theme form _self %} {% block _form_url_row %} <div class="url"> {{ form_label(form) }} {{ form_errors(form) }} {{ form_widget(form) }} </div> {% endblock %}
  • 25. Embedding a Collection of Forms // src/Volcano/VideoBundle/Form/Type/TagType.php class TagType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('name'); } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'VolcanoVideostatusBundleEntityTag', )); } public function getName() { return 'tag'; } }
  • 26. Embedding a Collection of Forms // src/Volcano/VideoBundle/Form/Type/ClipType.php class ClipType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('url','text'); $builder->add('timeStart', 'integer'); //... $builder->add('tags', 'collection', array( 'type' => new TagType(), 'allow_add' => true, 'allow_delete' => true ) ); } }