SlideShare a Scribd company logo
1 of 25
Download to read offline
Zend Framework Form, Subforms, DisplayGroups and Decorators



                           Zend Framework
                             Presentation
                       Mastering Zend Form Decorators




Nick Belhomme
                                                                    24 July 2009
PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
Zend Framework Form, Subforms, DisplayGroups and Decorators




   About Me:
   PHP5 Zend Certified Engineer (PHP5 ZCE)
   Zend Framework Certified Engineer (ZFCE)
   ZF Contributor since 2008
   Freelance Consultant
   PHP Community active member
Nick Belhomme
                                                                    24 July 2009
PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
Zend Framework Form, Subforms, DisplayGroups and Decorators




           Zend_Form
               Zend_Form_SubForm
                    Zend_Form_DisplayGroup




                Zend_Form_Element


               Zend_Form_Decorator_Interface

Nick Belhomme
                                                                    24 July 2009
PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
Zend Framework Form, Subforms, DisplayGroups and Decorators




                                    Zend_Form

                       • Provides an object oriented interface to
                       building forms.

                       • Allows DRY by extending
                       implementations.

                       • Allows the input validation and filtering.

                       • Allows logical grouping of form elements
                       to act like small forms or one big form

                       • Allows logical grouping of elements to
                       aid in display purposes.


Nick Belhomme
                                                                      24 July 2009
PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
Zend Framework Form, Subforms, DisplayGroups and Decorators




                       Zend_Form_SubForm

                        Creating logical element groups. Creating
                         multi-page forms. For instance Wizards.
                        Only once all sub forms validate would the
                              form be considered complete.




                               Create and Manipulate in Model




Nick Belhomme
                                                                     24 July 2009
PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
Zend Framework Form, Subforms, DisplayGroups and Decorators




                  Zend_Form_DisplayGroup

                        Display groups are a way to create virtual
                            groupings of elements for display
                        purposes. All elements in a display group
                        are rendered together. The most common
                        use case for this is for grouping elements
                                       in fieldsets.


                               Create and Manipulate in View




Nick Belhomme
                                                                     24 July 2009
PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
Zend Framework Form, Subforms, DisplayGroups and Decorators




                        Zend_Form_Element
                        Smallest part of the form. This represents
                        an object representation of a regular html
                                      form element.

                    This object is useful to:

                    • Bind filters to the input (Zend_Filter_Interface)

                    • Bind validators to the input (Zend_Validate_Interface)

                    • Bind Decorators (Zend_Form_Decorator_Interface)

                              Create and Manipulate in Model
                                  Bind Decorators in View
                             Set Metadata like class, id in View

Nick Belhomme
                                                                               24 July 2009
PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
Zend Framework Form, Subforms, DisplayGroups and Decorators




          Zend_Form_Decorator_Interface

                            Handles the markup of the form.
                        Implements the Decorator Design Pattern.
                        Thus the order in which you append them
                                      is important.



                               Create and Manipulate in View




Nick Belhomme
                                                                    24 July 2009
PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
Zend Framework Form, Subforms, DisplayGroups and Decorators




                              Assigning Roles

     Developers                                    Web Integrators (html, css)
     • Zend_Form_Element (Input handling) • Zend_Form_Decorator_Interface
     • Zend_Form_SubForm                  • Zend_Form_DisplayGroup
                                          • Zend_Form_Element (Metadata:
                                                   Class, Id)




Nick Belhomme
                                                                            24 July 2009
PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
Zend Framework Form, Subforms, DisplayGroups and Decorators




            Developers (controller - action)
              $form = new Zend_Form();
                  $form->setAction('/')
                     ->setMethod('post');

                   // Create and configure username element:
                   $username = $form->createElement('text', 'username');
                   $username->addValidator('alnum')
                         ->addValidator('regex', false, array('/^[a-z]+/'))
                         ->addValidator('stringLength', false, array(6, 20))
                         ->setRequired(true)
                         ->addFilter('StringToLower');




Nick Belhomme
                                                                               24 July 2009
PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
Zend Framework Form, Subforms, DisplayGroups and Decorators




            Developers (controller - action)
              // Create and configure password element:
                    $password = $form->createElement('password', 'password');
                    $password->addValidator('StringLength', false, array(6))
                         ->setRequired(true);

                   $submit = $form->createElement('submit', 'submit');
                   $submit->setIgnore(true);

                   // Add elements to form:
                   $form->addElement($username)
                       ->addElement($password)
                       ->addElement($submit);

                    $this->view->form = $form;


Nick Belhomme
                                                                          24 July 2009
PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
Zend Framework Form, Subforms, DisplayGroups and Decorators




                    Web Integrators (.phtml)
                        <?php
                        // Setup the form with attributes and use
                        // the markup of default decorators

                        $this->form->username->setLabel(‘user: ')
                                             ->setAttrib('id', ‘uName');

                        $this->form->password->setLabel('password: ')
                                             ->setAttrib('id', 'pwd');

                        $this->form->submit->setLabel(‘login');
                        ?>

                        <?php echo $this->form; ?>


Nick Belhomme
                                                                           24 July 2009
PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
Zend Framework Form, Subforms, DisplayGroups and Decorators




                    Web Integrators (.phtml)
                                Setup the form using
                       custom markup with the help of decorators

                   To understand how decorating works, you should
                 refresh your browser after each line of code you write.
                        You will see the form being build slowly.


                       <?php
                       // remove default markup:

                       $this->form->clearDecorators();

                       // now add the basic elements from the inside out
                       // (remember decorators use a strict order)


Nick Belhomme
                                                                           24 July 2009
PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
Zend Framework Form, Subforms, DisplayGroups and Decorators




                    Web Integrators (.phtml)
                 // First we have to decorate all form elements
                 // elements are input, checkbox, etc...

                 $this->form->setElementDecorators(array(
                       'viewHelper',
                       'label',
                       array('htmlTag', array('tag' => 'li')
                    ))
                 );

                 // Now we have told the form to render all the elements
                 // with their respective label
                 // and wrap them with a tag <li>



Nick Belhomme
                                                                           24 July 2009
PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
Zend Framework Form, Subforms, DisplayGroups and Decorators




                    Web Integrators (.phtml)
              // Then we have to tell the form to render the elements
              // so we are going to decorate the (emtpy form) with
              // the elements

              $this->form->addDecorator('formElements');

              // because we wrapped all elements and their labels with a
              // <li> tag we now should wrap all those with a <ul> tag.

              //$this->form->addDecorator('HtmlTag', array('tag' => 'ul'));




Nick Belhomme
                                                                              24 July 2009
PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
Zend Framework Form, Subforms, DisplayGroups and Decorators




                    Web Integrators (.phtml)
           // The elements are now printed to the screen in a nice UL list.
           // we now should wrap (decorate) the ul list with the <form> tag

           $this->form->addDecorator('form');




              Congratulations, you decorated your first decorated form.

                 It wasn’t that hard now was it? Once you understand
               On how decorating works and the order of the statements
                                   It really is that easy.




Nick Belhomme
                                                                              24 July 2009
PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
Zend Framework Form, Subforms, DisplayGroups and Decorators




                    Web Integrators (.phtml)
                 Let’s move on to adding fieldsets with displaygroups

                // first we define which elements should be inside the fieldset
                // then we define the internal name of the group
                // last we also tell the form not to use the default decorators
                // as we are going to decorate ourselves

                $this->form->addDisplayGroup(
                         array('username', 'password'),
                         'loginGroup',
                         array('disableLoadDefaultDecorators' => true));

         As you can see, username and password are not displayed
         anymore. This is because we wrapped them with the displaygroup
         and explicitely told the form not to render the group by disabling
         the default decorators. (The form doesn’t know how to render)
Nick Belhomme
                                                                                  24 July 2009
PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
Zend Framework Form, Subforms, DisplayGroups and Decorators



                    Web Integrators (.phtml)
              // give the form a clue on how to render the full form by decorating
              // the display groups
              // * first render the elements contained in the group
              // * wrap the elements with a <ul> tag
              // * wrap the <ul> tag with a fieldset
              // * wrap the fieldset with a <li> tag.

              $this->form->setDisplayGroupDecorators(array(
                  'formElements',
                  array(array('innerHtmlTag' => 'HtmlTag'), array('tag' => 'ul')),
                  'fieldset',
                  array(array('outerHtmlTag' => 'htmlTag'), array('tag' => 'li',
                                                                  'class' => 'myfieldset'))
              ));


                 As you can see, the order is very important. You are decorating!
                 The array(),array() construct is used because we are using multiple
                 htmlTag decorators at the same time, and thus we have to give them
                 a unique name. This is done in the first array construct.
Nick Belhomme
                                                                                         24 July 2009
PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
Zend Framework Form, Subforms, DisplayGroups and Decorators



                    Web Integrators (.phtml)


            // because by default elements not wrapped in a displayGroup
            // Are rendered first in the form, the order is not good.
            // we can easily modify the order of each element

            $this->form->loginGroup->setOrder(1);
            $this->form->submit->setOrder(2);




Nick Belhomme
                                                                           24 July 2009
PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
Zend Framework Form, Subforms, DisplayGroups and Decorators




                    Web Integrators (.phtml)


                          You created 3 forms! Congratulations.


                       I want you to create a fourth one. This will
                 not use lists, only fieldsets, divs, labels and elements

                       Solution is on the next page. Do not peek.
               (ok I shouldn’t have said the solution is on the next page,
                                   But try to resist ;) )




Nick Belhomme
                                                                             24 July 2009
PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
Zend Framework Form, Subforms, DisplayGroups and Decorators



                    Web Integrators (.phtml)
                      <?php
                      $this->form->clearDecorators();

                      $this->form->setElementDecorators(
                                array(
                                     'viewHelper',
                                     'label',
                                     array('htmlTag', array('tag' => 'div')),
                                  )
                      );
                      $this->form->addDecorator('formElements');
                      $this->form->addDecorator('form');

                      $this->form->addDisplayGroup(
                           array('username', 'password'),
                           'loginGroup',
                           array('disableLoadDefaultDecorators' => true)
                      );

Nick Belhomme
                                                                                24 July 2009
PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
Zend Framework Form, Subforms, DisplayGroups and Decorators



                    Web Integrators (.phtml)
                 $this->form->addDisplayGroup(
                    array('submit'),
                    'submitGroup',
                    array('disableLoadDefaultDecorators' => true)
                 );

                 $this->form->setDisplayGroupDecorators(array(
                     'formElements',
                     'fieldset',
                 ));

                 $this->form->username->setLabel('gebruikersnaam');
                 $this->form->password->setLabel('wachtwoord');
                 $this->form->submit->setLabel('login');
                 ?>
                 <?php echo $this->form; ?>

Nick Belhomme
                                                                      24 July 2009
PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
Zend Framework Form, Subforms, DisplayGroups and Decorators




                                  What about?
              Now that you have seen Zend_Form_Decorator_Interface
              Which uses the decorator pattern, maybe it is a good idea
              to tackle the other design patterns. Because knowing how
                to use the Zend Framework components doesn’t make
                           your Zend Framework application
                            easily maintainable and stable...

                      Design Patterns will help to achieve that goal.




Nick Belhomme
                                                                          24 July 2009
PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
Zend Framework Form, Subforms, DisplayGroups and Decorators




                  There is always next time!


                              1 hour courses, remember??? ;)

                                    Next: Design Patterns




Nick Belhomme
                                                                    24 July 2009
PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
Zend Framework Form, Subforms, DisplayGroups and Decorators




                                   Resources

    •http://blog.nickbelhomme.com
    •http://framework.zend.com/manual/en/zend.form.html
    •http://www.phppatterns.com/docs/design/decorator_pattern


    Source code of this workshop available at:
    http://blog.nickbelhomme.com/wp-content/uploads/workshopzf1.8forms.zip




Nick Belhomme
                                                                     24 July 2009
PHP5 Zend Certified Engineer + Zend Framework Certified Engineer

More Related Content

Similar to Zend Framework Form: Mastering Decorators

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
 
San Francisco PHP Meetup Presentation on Zend Framework
San Francisco PHP Meetup Presentation on Zend FrameworkSan Francisco PHP Meetup Presentation on Zend Framework
San Francisco PHP Meetup Presentation on Zend Framework
zend
 
Zend_Tool: Rapid Application Development with Zend Framework
Zend_Tool: Rapid Application Development with Zend FrameworkZend_Tool: Rapid Application Development with Zend Framework
Zend_Tool: Rapid Application Development with Zend Framework
Ralph Schindler
 
Why Zend Framework? - Meetup event!
Why Zend Framework? - Meetup event!Why Zend Framework? - Meetup event!
Why Zend Framework? - Meetup event!
AJINKYA N
 
Zend_Layout & Zend_View Enhancements
Zend_Layout & Zend_View EnhancementsZend_Layout & Zend_View Enhancements
Zend_Layout & Zend_View Enhancements
Ralph Schindler
 

Similar to Zend Framework Form: Mastering Decorators (20)

Getting up & running with zend framework
Getting up & running with zend frameworkGetting up & running with zend framework
Getting up & running with zend framework
 
Getting up and running with Zend Framework
Getting up and running with Zend FrameworkGetting up and running with Zend Framework
Getting up and running with Zend Framework
 
Disregard Inputs, Acquire Zend_Form
Disregard Inputs, Acquire Zend_FormDisregard Inputs, Acquire Zend_Form
Disregard Inputs, Acquire Zend_Form
 
A quick start on Zend Framework 2
A quick start on Zend Framework 2A quick start on Zend Framework 2
A quick start on Zend Framework 2
 
Zend Framework
Zend FrameworkZend Framework
Zend Framework
 
Introduction to Zend framework
Introduction to Zend framework Introduction to Zend framework
Introduction to Zend framework
 
Zend Framework 2 quick start
Zend Framework 2 quick startZend Framework 2 quick start
Zend Framework 2 quick start
 
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
 
ZFConf 2012: Zend Framework 2, a quick start (Enrico Zimuel)
ZFConf 2012: Zend Framework 2, a quick start (Enrico Zimuel)ZFConf 2012: Zend Framework 2, a quick start (Enrico Zimuel)
ZFConf 2012: Zend Framework 2, a quick start (Enrico Zimuel)
 
ZF2 Presentation @PHP Tour 2011 in Lille
ZF2 Presentation @PHP Tour 2011 in LilleZF2 Presentation @PHP Tour 2011 in Lille
ZF2 Presentation @PHP Tour 2011 in Lille
 
San Francisco PHP Meetup Presentation on Zend Framework
San Francisco PHP Meetup Presentation on Zend FrameworkSan Francisco PHP Meetup Presentation on Zend Framework
San Francisco PHP Meetup Presentation on Zend Framework
 
Zend_Tool: Rapid Application Development with Zend Framework
Zend_Tool: Rapid Application Development with Zend FrameworkZend_Tool: Rapid Application Development with Zend Framework
Zend_Tool: Rapid Application Development with Zend Framework
 
Framework Shootout ZF
Framework Shootout ZFFramework Shootout ZF
Framework Shootout ZF
 
Why Zend Framework? - Meetup event!
Why Zend Framework? - Meetup event!Why Zend Framework? - Meetup event!
Why Zend Framework? - Meetup event!
 
Working With The Symfony Admin Generator
Working With The Symfony Admin GeneratorWorking With The Symfony Admin Generator
Working With The Symfony Admin Generator
 
Zend Framework
Zend FrameworkZend Framework
Zend Framework
 
Using Zend_Tool to Establish Your Project's Skeleton
Using Zend_Tool to Establish Your Project's SkeletonUsing Zend_Tool to Establish Your Project's Skeleton
Using Zend_Tool to Establish Your Project's Skeleton
 
Quality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStormQuality assurance for php projects with PHPStorm
Quality assurance for php projects with PHPStorm
 
Zend_Layout & Zend_View Enhancements
Zend_Layout & Zend_View EnhancementsZend_Layout & Zend_View Enhancements
Zend_Layout & Zend_View Enhancements
 
Demo
DemoDemo
Demo
 

More from Nick Belhomme

Mastering selenium for automated acceptance tests
Mastering selenium for automated acceptance testsMastering selenium for automated acceptance tests
Mastering selenium for automated acceptance tests
Nick Belhomme
 
PHP traits, treat or threat?
PHP traits, treat or threat?PHP traits, treat or threat?
PHP traits, treat or threat?
Nick Belhomme
 

More from Nick Belhomme (6)

Vagrant move over, here is Docker
Vagrant move over, here is DockerVagrant move over, here is Docker
Vagrant move over, here is Docker
 
Mastering selenium for automated acceptance tests
Mastering selenium for automated acceptance testsMastering selenium for automated acceptance tests
Mastering selenium for automated acceptance tests
 
PHP traits, treat or threat?
PHP traits, treat or threat?PHP traits, treat or threat?
PHP traits, treat or threat?
 
PHP Quality Assurance Workshop PHPBenelux
PHP Quality Assurance Workshop PHPBeneluxPHP Quality Assurance Workshop PHPBenelux
PHP Quality Assurance Workshop PHPBenelux
 
Mastering Namespaces in PHP
Mastering Namespaces in PHPMastering Namespaces in PHP
Mastering Namespaces in PHP
 
Cursus phpunit
Cursus phpunitCursus phpunit
Cursus phpunit
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
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
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
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)
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
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
 
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...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 

Zend Framework Form: Mastering Decorators

  • 1. Zend Framework Form, Subforms, DisplayGroups and Decorators Zend Framework Presentation Mastering Zend Form Decorators Nick Belhomme 24 July 2009 PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
  • 2. Zend Framework Form, Subforms, DisplayGroups and Decorators About Me: PHP5 Zend Certified Engineer (PHP5 ZCE) Zend Framework Certified Engineer (ZFCE) ZF Contributor since 2008 Freelance Consultant PHP Community active member Nick Belhomme 24 July 2009 PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
  • 3. Zend Framework Form, Subforms, DisplayGroups and Decorators Zend_Form Zend_Form_SubForm Zend_Form_DisplayGroup Zend_Form_Element Zend_Form_Decorator_Interface Nick Belhomme 24 July 2009 PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
  • 4. Zend Framework Form, Subforms, DisplayGroups and Decorators Zend_Form • Provides an object oriented interface to building forms. • Allows DRY by extending implementations. • Allows the input validation and filtering. • Allows logical grouping of form elements to act like small forms or one big form • Allows logical grouping of elements to aid in display purposes. Nick Belhomme 24 July 2009 PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
  • 5. Zend Framework Form, Subforms, DisplayGroups and Decorators Zend_Form_SubForm Creating logical element groups. Creating multi-page forms. For instance Wizards. Only once all sub forms validate would the form be considered complete. Create and Manipulate in Model Nick Belhomme 24 July 2009 PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
  • 6. Zend Framework Form, Subforms, DisplayGroups and Decorators Zend_Form_DisplayGroup Display groups are a way to create virtual groupings of elements for display purposes. All elements in a display group are rendered together. The most common use case for this is for grouping elements in fieldsets. Create and Manipulate in View Nick Belhomme 24 July 2009 PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
  • 7. Zend Framework Form, Subforms, DisplayGroups and Decorators Zend_Form_Element Smallest part of the form. This represents an object representation of a regular html form element. This object is useful to: • Bind filters to the input (Zend_Filter_Interface) • Bind validators to the input (Zend_Validate_Interface) • Bind Decorators (Zend_Form_Decorator_Interface) Create and Manipulate in Model Bind Decorators in View Set Metadata like class, id in View Nick Belhomme 24 July 2009 PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
  • 8. Zend Framework Form, Subforms, DisplayGroups and Decorators Zend_Form_Decorator_Interface Handles the markup of the form. Implements the Decorator Design Pattern. Thus the order in which you append them is important. Create and Manipulate in View Nick Belhomme 24 July 2009 PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
  • 9. Zend Framework Form, Subforms, DisplayGroups and Decorators Assigning Roles Developers Web Integrators (html, css) • Zend_Form_Element (Input handling) • Zend_Form_Decorator_Interface • Zend_Form_SubForm • Zend_Form_DisplayGroup • Zend_Form_Element (Metadata: Class, Id) Nick Belhomme 24 July 2009 PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
  • 10. Zend Framework Form, Subforms, DisplayGroups and Decorators Developers (controller - action) $form = new Zend_Form(); $form->setAction('/') ->setMethod('post'); // Create and configure username element: $username = $form->createElement('text', 'username'); $username->addValidator('alnum') ->addValidator('regex', false, array('/^[a-z]+/')) ->addValidator('stringLength', false, array(6, 20)) ->setRequired(true) ->addFilter('StringToLower'); Nick Belhomme 24 July 2009 PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
  • 11. Zend Framework Form, Subforms, DisplayGroups and Decorators Developers (controller - action) // Create and configure password element: $password = $form->createElement('password', 'password'); $password->addValidator('StringLength', false, array(6)) ->setRequired(true); $submit = $form->createElement('submit', 'submit'); $submit->setIgnore(true); // Add elements to form: $form->addElement($username) ->addElement($password) ->addElement($submit); $this->view->form = $form; Nick Belhomme 24 July 2009 PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
  • 12. Zend Framework Form, Subforms, DisplayGroups and Decorators Web Integrators (.phtml) <?php // Setup the form with attributes and use // the markup of default decorators $this->form->username->setLabel(‘user: ') ->setAttrib('id', ‘uName'); $this->form->password->setLabel('password: ') ->setAttrib('id', 'pwd'); $this->form->submit->setLabel(‘login'); ?> <?php echo $this->form; ?> Nick Belhomme 24 July 2009 PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
  • 13. Zend Framework Form, Subforms, DisplayGroups and Decorators Web Integrators (.phtml) Setup the form using custom markup with the help of decorators To understand how decorating works, you should refresh your browser after each line of code you write. You will see the form being build slowly. <?php // remove default markup: $this->form->clearDecorators(); // now add the basic elements from the inside out // (remember decorators use a strict order) Nick Belhomme 24 July 2009 PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
  • 14. Zend Framework Form, Subforms, DisplayGroups and Decorators Web Integrators (.phtml) // First we have to decorate all form elements // elements are input, checkbox, etc... $this->form->setElementDecorators(array( 'viewHelper', 'label', array('htmlTag', array('tag' => 'li') )) ); // Now we have told the form to render all the elements // with their respective label // and wrap them with a tag <li> Nick Belhomme 24 July 2009 PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
  • 15. Zend Framework Form, Subforms, DisplayGroups and Decorators Web Integrators (.phtml) // Then we have to tell the form to render the elements // so we are going to decorate the (emtpy form) with // the elements $this->form->addDecorator('formElements'); // because we wrapped all elements and their labels with a // <li> tag we now should wrap all those with a <ul> tag. //$this->form->addDecorator('HtmlTag', array('tag' => 'ul')); Nick Belhomme 24 July 2009 PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
  • 16. Zend Framework Form, Subforms, DisplayGroups and Decorators Web Integrators (.phtml) // The elements are now printed to the screen in a nice UL list. // we now should wrap (decorate) the ul list with the <form> tag $this->form->addDecorator('form'); Congratulations, you decorated your first decorated form. It wasn’t that hard now was it? Once you understand On how decorating works and the order of the statements It really is that easy. Nick Belhomme 24 July 2009 PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
  • 17. Zend Framework Form, Subforms, DisplayGroups and Decorators Web Integrators (.phtml) Let’s move on to adding fieldsets with displaygroups // first we define which elements should be inside the fieldset // then we define the internal name of the group // last we also tell the form not to use the default decorators // as we are going to decorate ourselves $this->form->addDisplayGroup( array('username', 'password'), 'loginGroup', array('disableLoadDefaultDecorators' => true)); As you can see, username and password are not displayed anymore. This is because we wrapped them with the displaygroup and explicitely told the form not to render the group by disabling the default decorators. (The form doesn’t know how to render) Nick Belhomme 24 July 2009 PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
  • 18. Zend Framework Form, Subforms, DisplayGroups and Decorators Web Integrators (.phtml) // give the form a clue on how to render the full form by decorating // the display groups // * first render the elements contained in the group // * wrap the elements with a <ul> tag // * wrap the <ul> tag with a fieldset // * wrap the fieldset with a <li> tag. $this->form->setDisplayGroupDecorators(array( 'formElements', array(array('innerHtmlTag' => 'HtmlTag'), array('tag' => 'ul')), 'fieldset', array(array('outerHtmlTag' => 'htmlTag'), array('tag' => 'li', 'class' => 'myfieldset')) )); As you can see, the order is very important. You are decorating! The array(),array() construct is used because we are using multiple htmlTag decorators at the same time, and thus we have to give them a unique name. This is done in the first array construct. Nick Belhomme 24 July 2009 PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
  • 19. Zend Framework Form, Subforms, DisplayGroups and Decorators Web Integrators (.phtml) // because by default elements not wrapped in a displayGroup // Are rendered first in the form, the order is not good. // we can easily modify the order of each element $this->form->loginGroup->setOrder(1); $this->form->submit->setOrder(2); Nick Belhomme 24 July 2009 PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
  • 20. Zend Framework Form, Subforms, DisplayGroups and Decorators Web Integrators (.phtml) You created 3 forms! Congratulations. I want you to create a fourth one. This will not use lists, only fieldsets, divs, labels and elements Solution is on the next page. Do not peek. (ok I shouldn’t have said the solution is on the next page, But try to resist ;) ) Nick Belhomme 24 July 2009 PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
  • 21. Zend Framework Form, Subforms, DisplayGroups and Decorators Web Integrators (.phtml) <?php $this->form->clearDecorators(); $this->form->setElementDecorators( array( 'viewHelper', 'label', array('htmlTag', array('tag' => 'div')), ) ); $this->form->addDecorator('formElements'); $this->form->addDecorator('form'); $this->form->addDisplayGroup( array('username', 'password'), 'loginGroup', array('disableLoadDefaultDecorators' => true) ); Nick Belhomme 24 July 2009 PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
  • 22. Zend Framework Form, Subforms, DisplayGroups and Decorators Web Integrators (.phtml) $this->form->addDisplayGroup( array('submit'), 'submitGroup', array('disableLoadDefaultDecorators' => true) ); $this->form->setDisplayGroupDecorators(array( 'formElements', 'fieldset', )); $this->form->username->setLabel('gebruikersnaam'); $this->form->password->setLabel('wachtwoord'); $this->form->submit->setLabel('login'); ?> <?php echo $this->form; ?> Nick Belhomme 24 July 2009 PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
  • 23. Zend Framework Form, Subforms, DisplayGroups and Decorators What about? Now that you have seen Zend_Form_Decorator_Interface Which uses the decorator pattern, maybe it is a good idea to tackle the other design patterns. Because knowing how to use the Zend Framework components doesn’t make your Zend Framework application easily maintainable and stable... Design Patterns will help to achieve that goal. Nick Belhomme 24 July 2009 PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
  • 24. Zend Framework Form, Subforms, DisplayGroups and Decorators There is always next time! 1 hour courses, remember??? ;) Next: Design Patterns Nick Belhomme 24 July 2009 PHP5 Zend Certified Engineer + Zend Framework Certified Engineer
  • 25. Zend Framework Form, Subforms, DisplayGroups and Decorators Resources •http://blog.nickbelhomme.com •http://framework.zend.com/manual/en/zend.form.html •http://www.phppatterns.com/docs/design/decorator_pattern Source code of this workshop available at: http://blog.nickbelhomme.com/wp-content/uploads/workshopzf1.8forms.zip Nick Belhomme 24 July 2009 PHP5 Zend Certified Engineer + Zend Framework Certified Engineer