Bernhard Schussek
                        

Leveraging Symfony2 Forms 

    Symfony Live Conference, March 03rd 2011
About myself

 Software Architect in Vienna
 Student of Software 
 Engineering
 Symfony since 2006
 Outdoor and music junkie
Agenda

 Introductory example
 The Form Config class
 Form processing
 Fields
 Useful features
The Symfony2 Form 
    component
The Symfony2 Form component

 Evolution of symfony1 sfForm
 2.5 years development
 Fixes most of its problems
   Reusable widgets
   Embedded forms
Why 2.5 years?
"It takes a long time to make somthing 
complicated simple, but if you do, it will work 
without problems for a long time."

– F. Andy Seidl, http://faseidl.com
Service Oriented Architecture

 Applications provide services
 Services are exchangable
 These services can be consumed by different actors
   Humans
   Machines
Forms don't contain 
   business logic
Services do
Example: 
Online sausage shop
Example: Online sausage shop

        You
              Request

              Response
Example: Online sausage shop
Consumer                       Service

           You
                 Request

                 Response
Example: Online sausage shop
Consumer                       Service




              Request

             Response
Example: Online sausage shop
Consumer                       Service




              Request

             Response
Service implementation

  class Order
  {
      function setName($name);

      function setAddress($address);

      function setSausage($sausage);

      function setAmount($amount);
  }
Flow of information
                      I am Max!
Flow of information
                                  I am Max!




         $order->setName('Max')
Flow of information
   Order form

Name:    Max

Address: Sensio Labs,
         Paris

Sausage: Bratwurst

Amount: 5
Flow of information
   Order form
                        $order
Name:    Max            ->setName('Max')

Address: Sensio Labs,   ->setAddress(
                           'Sensio Labs,
         Paris
                            Paris')

Sausage: Bratwurst      ->setSausage(
                            'Bratwurst')
Amount: 5               ->setAmount(5);
Flow of information
                          Existing order
 $order
 ->getName()          Name:     Bob
 ->getAddress()       Address: Liip Office
                               Zurich

 ->getSausage()       Sausage: Cervelat

 ->getAmount();       Amount: 10
The Form Config class
Form definition
                   PHP class

  class OrderFormConfig extends AbstractConfig
  {
    public function configure(
         FieldInterface $form, array $options)
    {




      }
  }
Form definition
                   PHP class

  class OrderFormConfig extends AbstractConfig
  {
    public function configure(
         FieldInterface $form, array $options)
    {
      $form->add('text', 'name')
           ->add('text', 'address')
           ->add('text', 'sausage')
           ->add('integer', 'amount');
    }
  }
Form definition
                     PHP class

  class OrderFormConfig extends AbstractConfig
  {


      ...


      public function getIdentifier()
      {
        return 'form.order';
      }
  }
Why not a simple 
OrderForm class?
Why we need Config classes

 OrderForm cannot be put into the Dependency 
 Injection Container ...
 ... but OrderFormConfig can!
Dependency Injection Container
 <service id="form.order" class="OrderFormConfig">
   <tag name="form.config" alias="form.order" />
   <argument type="service" id="form.factory" />
 </service>


           Tag alias == form identifier

                      public function getIdentifier()
                      {
                        return 'form.order';
                      }
Form processing
Form processing                        Form identifier

  $factory = $this->get('form.factory');
  $form = $factory->getInstance('form.order');

  $form->setData($order);

  if ($request->getMethod() === 'POST') {
    $form->bindRequest($request);

      if ($form->isValid()) {
        $order->send();
        return new RedirectResponse(...);
      }
  }
Form processing
  $factory = $this->get('form.factory');
  $form = $factory->getInstance('form.order');

  $form->setData($order);          Service object
  if ($request->getMethod() === 'POST') {
    $form->bindRequest($request);

      if ($form->isValid()) {
        $order->send();
        return new RedirectResponse(...);
      }
  }
Form processing
  $factory = $this->get('form.factory');
  $form = $factory->getInstance('form.order');

  $form->setData($order);

  if ($request->getMethod() === 'POST') {
    $form->bindRequest($request);

      if ($form->isValid()) {      Calls setters
        $order->send();
        return new RedirectResponse(...);
      }
  }
Form processing
  $factory = $this->get('form.factory');
  $form = $factory->getInstance('form.order');

  $form->setData($order);

  if ($request->getMethod() === 'POST') {
    $form->bindRequest($request);

      if ($form->isValid()) {
        $order->send();
        return new RedirectResponse(...);
      }
  }         $order now contains submitted data!
Form rendering
                   In the action


  return $this->render(
      'HelloBundle:Hello:index.twig.html',
      array('form' => $form->getRenderer()));




               Contains view variables and methods
Form rendering
                 In the template


  <form action="#" method="post">
    {{ form.widget }}
  </form>




               "widget" is a view method
Form rendering
                           "fields" is a view variable


  <form action="#" method="post">
    {{ form.errors }}
    {% for field in form.vars.fields %}
      {{ field.errors }}
      {{ field.label }}
      {{ field.widget }}
    {% endfor %}
    {{ form.rest }}
  </form>
Form rendering

  <form action="#" method="post">
    {{ form.errors }}
    {{ form.name.errors }}
    {{ form.name.label }}
    {{ form.name.widget }}
    {{ form.rest }}
  </form>
Form rendering

  {{ form.rest }}



 Renders all fields that weren't rendered before
   ... fields that you forgot to render manually
   ... hidden fields
What about validation?
Form validation

 uses the Symfony2 Validator
 "Constraints" are put onto your PHP classes 
 (services, entities etc.)
Validation constraints

  class Order
  {
      /**
       * @check:NotNull
       * @check:AssertType("string")
       * @check:MaxLength(50, message=
       *                "Long name, dude...")
       */
      private $name;
  }
Fields
Text input

      Title:


      $form->add('text', 'title');
Textarea

   Content:



      $form->add('textarea', 'content');
Date selector
                           Mmmh localized!



     Publish at:


     $form->add('date', 'publishAt');
Country selector
                         Localized too! Yummy!



        Nationality:


    $form->add('country', 'nationality');
File upload

 Profile picture:


      $form->add('file', 'profilePicture');




                    Remembers uploaded files on errors!
Repeated input
           Email:
    Email (again):


       $form->add('repeated', 'email');
Core fields
               entity
  birthday                password
               file
  checkbox                percent
               hidden
  choice                  repeated
               integer
  collection              textarea
               language
  country                 text
               locale
  date                    timezone
               money
  datetime                url
               number
Field architecture

  Filters
  Value transformers
Filters

  modify a value
  uni­directional
  Example: FixUrlProtocolFilter

  symfony-project.com      http://symfony-project.com
Value Transformers

 convert values between two representations
 bi­directional
 Example: DateTimeToArrayTransformer

                                array(
                                  'year' => 2011,
  object(DateTime)                'month' => 5,
                                  'day' => 1,
                                )
Example: Entity field
The user sees:



Symfony sees:

    Entity field
       Checkbox    Checkbox   Checkbox   Checkbox
          "0"         "1"        "2"        "3"


                               Tag IDs
Tag IDs

array("0" => "0", "1" => "1", "2" => "1", ...)




  "0"          "1"          "0"          "0"


Checkbox    Checkbox      Checkbox     Checkbox
   "0"         "1"           "2"          "3"
Tag IDs

array("0" => "0", "1" => "1", "2" => "1", ...)




  "0"          "1"          "0"          "0"


Checkbox    Checkbox      Checkbox     Checkbox
   "0"         "1"           "2"          "3"
Checkbox      Checkbox     Checkbox     Checkbox
     "0"           "1"          "2"          "3"



    false         true         true         false




array("0" => false, "1" => true, "2" => true, ...)




   ArrayCollection($securityTag, $validatorTag)
Checkbox      Checkbox     Checkbox     Checkbox
     "0"           "1"          "2"          "3"



    false         true         true         false


                            ChoicesToArrayTransformer

array("0" => false, "1" => true, "2" => true, ...)




   ArrayCollection($securityTag, $validatorTag)
Checkbox      Checkbox     Checkbox     Checkbox
     "0"           "1"          "2"          "3"



    false         true         true         false




array("0" => false, "1" => true, "2" => true, ...)

                            ArrayToEntitiesTransformer

   ArrayCollection($securityTag, $validatorTag)
CSRF protection

 Cross­Site Request Forgery
 A form is submitted using the session of another 
 person
 All kinds of misuse


 Built­in protection in Symfony2
CSRF protection

              app/config/config.yml


  framework:
      csrf_protection:
          enabled: true
          secret: 30665e19ef0010d5620553
Field creation

  Manual
  Automatic
    Symfony2 looks at metadata of the domain class to 
    "guess" the correct field type and settings
    E.g. Validator metadata, Doctrine2 metadata
Manual field creation
  public function configure(
       FieldInterface $form, array $options)
  {
    $form->add('entity', 'sausage', array(
      'class' => 'Sausage',
    ));
  }


 but Doctrine already knows, that "sausage" is a 
 To­One relationship to the Sausage class!
Automatic field creation
  public function configure(
       FieldInterface $form, array $options)
  {
    $form->setDataClass('Order');

      $form->add('sausage');
  }
Automatic with options overriding
  public function configure(
       FieldInterface $form, array $options)
  {
    $form->setDataClass('Order')
         ->add('sausage', array(
           'required' => false,
         ));
  }
Embedded forms

 Symfony2 allows to embed forms into another very 
 easily
 Fields and forms implement FieldInterface
 "A form is a field"
Embedded to­one forms

  public function configure(
       FieldInterface $form, array $options)
  {
    $form->add('form.sausage', 'sausage');
  }


  Identifier of SausageFormConfig
Embedded to­many forms

  public function configure(
        FieldInterface $form, array $options)
  {
    $form->add('collection', 'sausages', array(
      'identifier' => 'form.sausage'
    ));
  }


           Identifier of SausageFormConfig
Config options

 Options for influencing the field's/form's creation

  class ConcealedFieldConfig extends Abstract..
  {
    public function getDefaultOptions($options)
    {
      return array(
        'concealed' => true,
      );
    }
  }
Config inheritance

 Dynamic inheritance from other forms/fields

  class ConcealedFieldConfig extends Abstract..
  {
    public function getParent(array $options)
    {
      return $options['concealed']
          ? 'password' : 'text';
    }
  }
Form themes

 Are normal Twig templates
 Blocks for each field type

  {% block textarea__widget %}
    <textarea {{ block('attributes') }}>
      {{ value }}
    </textarea>
  {% endblock textarea__widget %}
Form themes

 Can specify widget, errors, label and row 
 templates for specific field types

  {% block textarea__row %}
    <tr><td colspan="2">
      {{ this.errors }}
      {{ this.widget }}
    </td></tr>
  {% endblock textarea__row %}
Form themes

 Core themes:
   TwigBundle::div_layout.html.twig
   TwigBundle::table_layout.html.twig
 Configuration in the DI parameter 
 "form.theme.template"
 More flexible configuration options coming soon
Questions?




                 Thanks for listening!

              Code can currently be found on
https://github.com/bschussek/symfony/tree/experimental

                  Bernhard Schussek
                 Twitter: @webmozart
The End




Copyright

"dog window" by Larry Wentzel
http://www.flickr.com/photos/wentzelepsy

"Symfony Live 2011 Logo" by Sensio Labs
http://www.sensiolabs.com

Leveraging Symfony2 Forms