SlideShare uma empresa Scribd logo
1 de 58
Baixar para ler offline
The new form framework
Bernhard Schussek
What is different in the new form
           framework?
symfony 1.x
          User


         sfForm



        Controller


      Domain Model
symfony 1.x
          User


         sfForm


                     Business Logic
        Controller


      Domain Model
symfony 1.x
          User


         sfForm


                     Business Logic
        Controller


      Domain Model    unit testable!!
symfony 1.x
              User


                                  function configure()
                                  {
                                    unset($this['foo']);
  sfFormDoctrine / sfFormPropel     unset($this['bar']);
                                    unset($this['moo']);
                                    unset($this['comeon!']);
                                    ...




         Domain Model
New architecture
Simplicity and Reusability
Embrace your domain model
Symfony 2
          User


         Form




      Domain Model
Symfony 2
          User
                           Presentation
         Form




      Domain Model         Business Logic



                     designed by you™
Business Logic


class Customer
{

    public $name = 'Default';


    public getGender();

    public setGender($gender);

}
Business Logic                Presentation


class Customer                               Form
{
                                 TextField
    public $name = 'Default';


    public getGender();          ChoiceField
    public setGender($gender);

}
$form = new Form('customer', $customer, ...);

$form->add(new TextField('name'));

$form->add(new ChoiceField('gender', array(
  'choices' => array('male', 'female'),
)));
$form = new Form('customer', $customer, ...);

...

if (isset($_POST['customer']))
{
  $form->bind($_POST['customer']);
}
Business Logic       Presentation




class Customer                     Form
{
            to-one relations    FieldGroup
    public $address;


}
$group = new FieldGroup('address');

$group->add(...);
$group->add(...);
$group->add(...);

$form->add($group);
Business Logic          Presentation

class Customer                        Form
{
                                  CollectionField
              to-many relations    FieldGroup
    public $emails;

                                   FieldGroup



}
$group = new FieldGroup('emails');

$group->add(...);
$group->add(...);

$form->add(new CollectionField($group));
Default                       Localized

  TextField     NumberField                 TimeField

TextareaField   IntegerField            DateTimeField

CheckboxField   PercentField            TimezoneField

 ChoiceField    MoneyField              RepeatedField

PasswordField    DateField              CollectionField

 HiddenField    BirthdayField               FieldGroup

                                             Special
●   Field groups
    —   light-weight subforms
    —   compose other fields or field groups
                                      ?

                     DateField

              ChoiceField                 ChoiceField


    CheckboxField     CheckboxField
Form Rendering
<?php echo $form->renderFormTag('url') ?>

  <?php echo $form->renderErrors() ?>
  <?php echo $form->render() ?>

  <input type="submit" value="Submit" />

</form>
<label for="<?php echo $form['name']->getId() ?>">
  Enter a name
</label>

<?php echo $form['name']->renderErrors() ?>
<?php echo $form['name']->render() ?>
<?php echo $form['date']['day']->render() ?>
<?php echo $form['date']['month']->render() ?>
<?php echo $form['date']['year']->render() ?>
Validation
symfony 1.x
          sfForm
        sfValidator


         Controller


      Domain Model
     Doctrine_Validator
symfony 1.x
          sfForm
        sfValidator


         Controller       Duplicate validation
                                 logic

      Domain Model
     Doctrine_Validator    Failed validation
                           leads to 505 errors
Symfony 2


         Form



      Domain Model
Symfony 2


         Form

                     Validator

      Domain Model
Symfony 2


         Form

                                          Validator

      Domain Model


                                    Validation Metadata

                "how shall the domain model be validated?"
Customer:
  properties:
    name:
      - MinLength: 6
    birthday:
      - Date: ~
    gender:
      - Choice: [male, female]
<class name="Customer">
  <property name="name">
    <constraint name="MinLength">6</constraint>
  </property>
  <property name="birthday">
    <constraint name="Date" />
  </property>
  <property name="gender">
    <constraint name="Choice">
      <value>male</value>
      <value>female</value>
    </constraint>
  </property>
</class>
class Customer
{
  /** @Validation({ @MinLength(6) }) */
  public $name;

    /** @Validation({ @Choice({"male", "female"}) }) */
    public function getGender();

    /** @Validation({ @Valid }) */
    public $gender;
}
Type Check            String       Other

AssertTrue        AssertType   MinLength      Min

AssertFalse            Date    MaxLength     Max

  Blank            DateTime      Regex      Choice

NotBlank               Time       Url        Valid

   Null                          Email     Collection

 NotNull                                      File
●   Constraints can be put on
    —   Classes
    —   Properties
    —   Methods with a "get" or "is" prefix
$validator = $container->getService('validator');

$validator->validate($customer);
Independent from Symfony 2


 Zend    Doctrine 2   Propel
How does all this fit into the form
         framework?
$form = new Form('customer', $customer,
    $this->container->getService('validator'));
$form->bind($_POST['customer']);

if ($form->isValid())
{
  // do something with $customer
}
●   The validation is launched automatically
    upon submission
Common Questions
Q: What if my form does not translate
      1:1 to a domain model?
A: Then the domain model doesn't
            exist yet ;-)
●   Use Case
    —   Extend our form for a checkbox to accept terms
        and conditions
    —   Should not be stored as field in the Customer
        class
class Registration {
  /** @Validation({ @Valid }) */
  public $customer;

    /**
     * @Validation({
     *    @AssertTrue(message="Please accept")
     * })
     */
    public $termsAccepted = false;

    public function process() {
      // save $customer, send emails etc.
    }
}
$form->add(new CheckboxField('termsAccepted'));

$group = new FieldGroup('customer');
$group->add(new TextField('name'));
...

$form->add($group);
if ($form->isValid())
{
  $registration->process();
}
●   The Registration class
    —   can be reused (XML requests, …)
    —   can be unit tested
Q: What if I don't want to validate all
     attributes of an object?
A: Use Constraint groups
●   Use Case
    —   Administrators should be able to create
        Customers with empty names
    —   Normal users not
class Customer
{
  /**
   * @Validation({
   *    @NotBlank(groups="User")
   * })
   */
  public $name;

    ...
}
$validator->validate($customer, 'User');
$form->setValidationGroups('User');
$form->bind($_POST('customer'));

if ($form->isValid())
{
  ...
}
●   Constraint groups can be sequenced
    —   first validate group "Fast"
    —   then, if "Fast" was valid, validate group "Slow"
Questions?

Mais conteúdo relacionado

Mais procurados

Ruby on Rails For Java Programmers
Ruby on Rails For Java ProgrammersRuby on Rails For Java Programmers
Ruby on Rails For Java Programmers
elliando dias
 
Jquery presentation
Jquery presentationJquery presentation
Jquery presentation
guest5d87aa6
 

Mais procurados (17)

Data Validation models
Data Validation modelsData Validation models
Data Validation models
 
D8 Form api
D8 Form apiD8 Form api
D8 Form api
 
ZG PHP - Specification
ZG PHP - SpecificationZG PHP - Specification
ZG PHP - Specification
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
November Camp - Spec BDD with PHPSpec 2
November Camp - Spec BDD with PHPSpec 2November Camp - Spec BDD with PHPSpec 2
November Camp - Spec BDD with PHPSpec 2
 
Curso Symfony - Clase 4
Curso Symfony - Clase 4Curso Symfony - Clase 4
Curso Symfony - Clase 4
 
Sylius and Api Platform The story of integration
Sylius and Api Platform The story of integrationSylius and Api Platform The story of integration
Sylius and Api Platform The story of integration
 
Zend framework 04 - forms
Zend framework 04 - formsZend framework 04 - forms
Zend framework 04 - forms
 
Curso Symfony - Clase 2
Curso Symfony - Clase 2Curso Symfony - Clase 2
Curso Symfony - Clase 2
 
Business Rules with Brick
Business Rules with BrickBusiness Rules with Brick
Business Rules with Brick
 
Forget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers CracowForget about Index.php and build you applications around HTTP - PHPers Cracow
Forget about Index.php and build you applications around HTTP - PHPers Cracow
 
Neo4 J
Neo4 J Neo4 J
Neo4 J
 
Cloud Entwicklung mit Apex
Cloud Entwicklung mit ApexCloud Entwicklung mit Apex
Cloud Entwicklung mit Apex
 
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
 
Ruby on Rails For Java Programmers
Ruby on Rails For Java ProgrammersRuby on Rails For Java Programmers
Ruby on Rails For Java Programmers
 
Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)
 
Jquery presentation
Jquery presentationJquery presentation
Jquery presentation
 

Destaque

The state of Symfony2 - SymfonyDay 2010
The state of Symfony2 - SymfonyDay 2010The state of Symfony2 - SymfonyDay 2010
The state of Symfony2 - SymfonyDay 2010
Fabien Potencier
 
Symfony As A Platform (Symfony Camp 2007)
Symfony As A Platform (Symfony Camp 2007)Symfony As A Platform (Symfony Camp 2007)
Symfony As A Platform (Symfony Camp 2007)
Fabien Potencier
 
Speed up your developments with Symfony2
Speed up your developments with Symfony2Speed up your developments with Symfony2
Speed up your developments with Symfony2
Hugo Hamon
 
Symfony2 and Doctrine2 Integration
Symfony2 and Doctrine2 IntegrationSymfony2 and Doctrine2 Integration
Symfony2 and Doctrine2 Integration
Jonathan Wage
 

Destaque (20)

The state of Symfony2 - SymfonyDay 2010
The state of Symfony2 - SymfonyDay 2010The state of Symfony2 - SymfonyDay 2010
The state of Symfony2 - SymfonyDay 2010
 
Debugging With Symfony
Debugging With SymfonyDebugging With Symfony
Debugging With Symfony
 
Plugins And Making Your Own
Plugins And Making Your OwnPlugins And Making Your Own
Plugins And Making Your Own
 
PHP, Cloud And Microsoft Symfony Live 2010
PHP,  Cloud And  Microsoft    Symfony  Live 2010PHP,  Cloud And  Microsoft    Symfony  Live 2010
PHP, Cloud And Microsoft Symfony Live 2010
 
Symfony As A Platform (Symfony Camp 2007)
Symfony As A Platform (Symfony Camp 2007)Symfony As A Platform (Symfony Camp 2007)
Symfony As A Platform (Symfony Camp 2007)
 
Decoupling Content Management with Create.js and PHPCR
Decoupling Content Management with Create.js and PHPCRDecoupling Content Management with Create.js and PHPCR
Decoupling Content Management with Create.js and PHPCR
 
What Symfony Has To Do With My Garage - Home Automation With PHP
What Symfony Has To Do With My Garage - Home Automation With PHPWhat Symfony Has To Do With My Garage - Home Automation With PHP
What Symfony Has To Do With My Garage - Home Automation With PHP
 
Symfony Internals
Symfony InternalsSymfony Internals
Symfony Internals
 
OkAPI meet symfony, symfony meet OkAPI
OkAPI meet symfony, symfony meet OkAPIOkAPI meet symfony, symfony meet OkAPI
OkAPI meet symfony, symfony meet OkAPI
 
Speed up your developments with Symfony2
Speed up your developments with Symfony2Speed up your developments with Symfony2
Speed up your developments with Symfony2
 
How to Clear Cache in a Symfony Cross Application
How to Clear Cache in a Symfony Cross ApplicationHow to Clear Cache in a Symfony Cross Application
How to Clear Cache in a Symfony Cross Application
 
Symfony in the Cloud
Symfony in the CloudSymfony in the Cloud
Symfony in the Cloud
 
Apostrophe
ApostropheApostrophe
Apostrophe
 
Symfony2 and Doctrine2 Integration
Symfony2 and Doctrine2 IntegrationSymfony2 and Doctrine2 Integration
Symfony2 and Doctrine2 Integration
 
Doctrine in the Real World
Doctrine in the Real WorldDoctrine in the Real World
Doctrine in the Real World
 
Developing for Developers
Developing for DevelopersDeveloping for Developers
Developing for Developers
 
Doctrine Php Object Relational Mapper
Doctrine Php Object Relational MapperDoctrine Php Object Relational Mapper
Doctrine Php Object Relational Mapper
 
Symfony and eZ Publish
Symfony and eZ PublishSymfony and eZ Publish
Symfony and eZ Publish
 
Symfony2 revealed
Symfony2 revealedSymfony2 revealed
Symfony2 revealed
 
Implementing a Symfony Based CMS in a Publishing Company
Implementing a Symfony Based CMS in a Publishing CompanyImplementing a Symfony Based CMS in a Publishing Company
Implementing a Symfony Based CMS in a Publishing Company
 

Semelhante a The new form framework

Zend_Form to the Rescue - A Brief Introduction to Zend_Form
Zend_Form to the Rescue - A Brief Introduction to Zend_FormZend_Form to the Rescue - A Brief Introduction to Zend_Form
Zend_Form to the Rescue - A Brief Introduction to Zend_Form
Jeremy Kendall
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friends
Michael Peacock
 
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf Conference
 
symfony on action - WebTech 207
symfony on action - WebTech 207symfony on action - WebTech 207
symfony on action - WebTech 207
patter
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)
Fabien Potencier
 

Semelhante a The new form framework (20)

Михаил Крайнюк - 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
 
Zend_Form to the Rescue - A Brief Introduction to Zend_Form
Zend_Form to the Rescue - A Brief Introduction to Zend_FormZend_Form to the Rescue - A Brief Introduction to Zend_Form
Zend_Form to the Rescue - A Brief Introduction to Zend_Form
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friends
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
Migrare da symfony 1 a Symfony2
 Migrare da symfony 1 a Symfony2  Migrare da symfony 1 a Symfony2
Migrare da symfony 1 a Symfony2
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2
 
Symfony tips and tricks
Symfony tips and tricksSymfony tips and tricks
Symfony tips and tricks
 
Working With The Symfony Admin Generator
Working With The Symfony Admin GeneratorWorking With The Symfony Admin Generator
Working With The Symfony Admin Generator
 
Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8Unit testing after Zend Framework 1.8
Unit testing after Zend Framework 1.8
 
SOLID PRINCIPLES
SOLID PRINCIPLESSOLID PRINCIPLES
SOLID PRINCIPLES
 
So S.O.L.I.D Fu - Designing Better Code
So S.O.L.I.D Fu - Designing Better CodeSo S.O.L.I.D Fu - Designing Better Code
So S.O.L.I.D Fu - Designing Better Code
 
WordPress REST API hacking
WordPress REST API hackingWordPress REST API hacking
WordPress REST API hacking
 
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
 
symfony on action - WebTech 207
symfony on action - WebTech 207symfony on action - WebTech 207
symfony on action - WebTech 207
 
関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい関西PHP勉強会 php5.4つまみぐい
関西PHP勉強会 php5.4つまみぐい
 
Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)Be RESTful (Symfony Camp 2008)
Be RESTful (Symfony Camp 2008)
 
Gérer vos objets
Gérer vos objetsGérer vos objets
Gérer vos objets
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
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...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
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
 
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)
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
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...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
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
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
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...
 
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
 
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, ...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 

The new form framework

  • 1. The new form framework Bernhard Schussek
  • 2. What is different in the new form framework?
  • 3. symfony 1.x User sfForm Controller Domain Model
  • 4. symfony 1.x User sfForm Business Logic Controller Domain Model
  • 5. symfony 1.x User sfForm Business Logic Controller Domain Model unit testable!!
  • 6. symfony 1.x User function configure() { unset($this['foo']); sfFormDoctrine / sfFormPropel unset($this['bar']); unset($this['moo']); unset($this['comeon!']); ... Domain Model
  • 10. Symfony 2 User Form Domain Model
  • 11. Symfony 2 User Presentation Form Domain Model Business Logic designed by you™
  • 12. Business Logic class Customer { public $name = 'Default'; public getGender(); public setGender($gender); }
  • 13. Business Logic Presentation class Customer Form { TextField public $name = 'Default'; public getGender(); ChoiceField public setGender($gender); }
  • 14. $form = new Form('customer', $customer, ...); $form->add(new TextField('name')); $form->add(new ChoiceField('gender', array( 'choices' => array('male', 'female'), )));
  • 15. $form = new Form('customer', $customer, ...); ... if (isset($_POST['customer'])) { $form->bind($_POST['customer']); }
  • 16. Business Logic Presentation class Customer Form { to-one relations FieldGroup public $address; }
  • 17. $group = new FieldGroup('address'); $group->add(...); $group->add(...); $group->add(...); $form->add($group);
  • 18. Business Logic Presentation class Customer Form { CollectionField to-many relations FieldGroup public $emails; FieldGroup }
  • 19. $group = new FieldGroup('emails'); $group->add(...); $group->add(...); $form->add(new CollectionField($group));
  • 20. Default Localized TextField NumberField TimeField TextareaField IntegerField DateTimeField CheckboxField PercentField TimezoneField ChoiceField MoneyField RepeatedField PasswordField DateField CollectionField HiddenField BirthdayField FieldGroup Special
  • 21. Field groups — light-weight subforms — compose other fields or field groups ? DateField ChoiceField ChoiceField CheckboxField CheckboxField
  • 23. <?php echo $form->renderFormTag('url') ?> <?php echo $form->renderErrors() ?> <?php echo $form->render() ?> <input type="submit" value="Submit" /> </form>
  • 24. <label for="<?php echo $form['name']->getId() ?>"> Enter a name </label> <?php echo $form['name']->renderErrors() ?> <?php echo $form['name']->render() ?>
  • 25. <?php echo $form['date']['day']->render() ?> <?php echo $form['date']['month']->render() ?> <?php echo $form['date']['year']->render() ?>
  • 27. symfony 1.x sfForm sfValidator Controller Domain Model Doctrine_Validator
  • 28. symfony 1.x sfForm sfValidator Controller Duplicate validation logic Domain Model Doctrine_Validator Failed validation leads to 505 errors
  • 29. Symfony 2 Form Domain Model
  • 30. Symfony 2 Form Validator Domain Model
  • 31. Symfony 2 Form Validator Domain Model Validation Metadata "how shall the domain model be validated?"
  • 32. Customer: properties: name: - MinLength: 6 birthday: - Date: ~ gender: - Choice: [male, female]
  • 33. <class name="Customer"> <property name="name"> <constraint name="MinLength">6</constraint> </property> <property name="birthday"> <constraint name="Date" /> </property> <property name="gender"> <constraint name="Choice"> <value>male</value> <value>female</value> </constraint> </property> </class>
  • 34. class Customer { /** @Validation({ @MinLength(6) }) */ public $name; /** @Validation({ @Choice({"male", "female"}) }) */ public function getGender(); /** @Validation({ @Valid }) */ public $gender; }
  • 35. Type Check String Other AssertTrue AssertType MinLength Min AssertFalse Date MaxLength Max Blank DateTime Regex Choice NotBlank Time Url Valid Null Email Collection NotNull File
  • 36. Constraints can be put on — Classes — Properties — Methods with a "get" or "is" prefix
  • 38. Independent from Symfony 2 Zend Doctrine 2 Propel
  • 39. How does all this fit into the form framework?
  • 40. $form = new Form('customer', $customer, $this->container->getService('validator'));
  • 42. The validation is launched automatically upon submission
  • 44. Q: What if my form does not translate 1:1 to a domain model?
  • 45. A: Then the domain model doesn't exist yet ;-)
  • 46. Use Case — Extend our form for a checkbox to accept terms and conditions — Should not be stored as field in the Customer class
  • 47. class Registration { /** @Validation({ @Valid }) */ public $customer; /** * @Validation({ * @AssertTrue(message="Please accept") * }) */ public $termsAccepted = false; public function process() { // save $customer, send emails etc. } }
  • 48. $form->add(new CheckboxField('termsAccepted')); $group = new FieldGroup('customer'); $group->add(new TextField('name')); ... $form->add($group);
  • 49. if ($form->isValid()) { $registration->process(); }
  • 50. The Registration class — can be reused (XML requests, …) — can be unit tested
  • 51. Q: What if I don't want to validate all attributes of an object?
  • 53. Use Case — Administrators should be able to create Customers with empty names — Normal users not
  • 54. class Customer { /** * @Validation({ * @NotBlank(groups="User") * }) */ public $name; ... }
  • 57. Constraint groups can be sequenced — first validate group "Fast" — then, if "Fast" was valid, validate group "Slow"