Zend Form to the Rescue!
A Brief Introduction to Zend_Form
About Me
Jeremy Kendall
PHP Developer since 2001
Organizer Memphis PHP (MemphisPHP.org)
Contributor to FRAPI project (getF...
Forms in General
● Ubiquitous
● Tedious
● Challenging to get right
● Security risk
● Primary job responsibility
Typical Form Requirements
● Collect data
● Filter input
● Validate input
● Display validation messages
● Include default d...
Typical PHP Form
● Tons of markup
● Tons of code
● Confusing conditionals
● Client side validation likely
● Server side va...
Zend Form to the Rescue!
● Introduced in ZF 1.5, early 2008
● Generates markup
● Filters and validates user input
● Displa...
Standard Form Elements
● Button
● Captcha
● Checkbox
● File
● Hidden
● Hash
● Image
● MultiCheckbox
● MultiSelect
● Passwo...
Standard Filter Classes
● Alnum
● Alpha
● Basename
● Boolean
● HtmlEntities
● StringToLower
● StringToUpper
● StringTrim
●...
Standard Validation Classes
● Alnum
● Alpha
● Barcode
● Between
● Callback
● CreditCard
● Date
● Db
● RecordExists
● NoRec...
Simple Contact Form
<?php
class Application_Form_Contact extends Zend_Form
{
public function init()
{
// Form elements and...
Simple Contact Form
<?php
class Application_Form_Contact extends Zend_Form
{
public function init()
{
// Form elements and...
Simple Contact Form
<?php
class Application_Form_Contact extends Zend_Form
{
public function init()
{
// Form elements and...
Name Element
$name = new Zend_Form_Element_Text('name');
$name->setLabel('Your name');
$name->setRequired(true);
$name->ad...
Name Element
$name = new Zend_Form_Element_Text('name');
$name->setLabel('Your name');
$name->setRequired(true);
$name->ad...
Name Element
$name = new Zend_Form_Element_Text('name');
$name->setLabel('Your name');
$name->setRequired(true);
$name->ad...
Name Element
$name = new Zend_Form_Element_Text('name');
$name->setLabel('Your name');
$name->setRequired(true);
$name->ad...
Name Element
$name = new Zend_Form_Element_Text('name');
$name->setLabel('Your name');
$name->setRequired(true);
$name->ad...
Name Element
$name = new Zend_Form_Element_Text('name');
$name->setLabel('Your name');
$name->setRequired(true);
$name->ad...
Email Element
$email = new Zend_Form_Element_Text('email');
$email->setLabel('Email Address');
$email->setRequired(true);
...
Email Element
$email = new Zend_Form_Element_Text('email');
$email->setLabel('Email Address');
$email->setRequired(true);
...
Message Element
$message = new Zend_Form_Element_Textarea('message');
$message->setLabel('Whatcha got to say?');
$message-...
Message Element
$message = new Zend_Form_Element_Textarea('message');
$message->setLabel('Whatcha got to say?');
$message-...
Submit Element
$submit = new Zend_Form_Element_Submit('submit');
$submit->setLabel('Make contact!');
$submit->setIgnore(tr...
Submit Element
$submit = new Zend_Form_Element_Submit('submit');
$submit->setLabel('Make contact!');
$submit->setIgnore(tr...
Add Filters to All Elements
$this->setElementFilters(array(
new Zend_Filter_StringTrim(),
new Zend_Filter_StripTags()
));
MVC Action
public function indexAction()
{
$form = new Application_Form_Contact();
$this->view->form = $form;
if (!$this->...
MVC Action
public function indexAction()
{
$form = new Application_Form_Contact();
$this->view->form = $form;
if (!$this->...
MVC Action
public function indexAction()
{
$form = new Application_Form_Contact();
$this->view->form = $form;
if (!$this->...
MVC Action
public function indexAction()
{
$form = new Application_Form_Contact();
$this->view->form = $form;
if (!$this->...
MVC Action
public function indexAction()
{
$form = new Application_Form_Contact();
$this->view->form = $form;
if (!$this->...
MVC Action
public function indexAction()
{
$form = new Application_Form_Contact();
$this->view->form = $form;
if (!$this->...
View
<?php echo $this->form; ?>
Default Markup
<form enctype="application/x-www-form-urlencoded" action=""
method="post">
<dl class="zend_form">
<dt id="n...
What does it look like?
How about with errors?
Can I use Zend Form by itself?
Standalone - library/base.php
<?php
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
...
Standalone - library/base.php
<?php
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
...
Standalone - library/base.php
<?php
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
...
Standalone - library/base.php
<?php
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
...
Standalone - library/base.php
<?php
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
...
Standalone – form script
<?php
require_once dirname(__FILE__) . '/library/base.php';
$form = new Application_Form_Contact(...
Standalone – form script
<?php
require_once dirname(__FILE__) . '/library/base.php';
$form = new Application_Form_Contact(...
Standalone – form script
<?php
require_once dirname(__FILE__) . '/library/base.php';
$form = new Application_Form_Contact(...
Standalone – form script
<?php
require_once dirname(__FILE__) . '/library/base.php';
$form = new Application_Form_Contact(...
Standalone – form script
<?php
require_once dirname(__FILE__) . '/library/base.php';
$form = new Application_Form_Contact(...
Standalone – form script
<?php
require_once dirname(__FILE__) . '/library/base.php';
$form = new Application_Form_Contact(...
Test time!
<?php
/**
* ContactFormTest
*/
class ContactFormTest extends PHPUnit_Framework_TestCase
{
// Setup, teardown, a...
Setting up our test
public function setUp()
{
parent::setUp();
$this->_form = new Application_Form_Contact();
$this->_data...
Setting up our test
public function setUp()
{
parent::setUp();
$this->_form = new Application_Form_Contact();
$this->_data...
Setting up our test
public function setUp()
{
parent::setUp();
$this->_form = new Application_Form_Contact();
$this->_data...
Test Valid Data
public function testValidDataPassesValidation()
{
$this->assertTrue($this->_form->isValid($this->_data));
}
Test Invalid Data
public function testShortNameInvalidatesForm()
{
$this->_data['name'] = 'Bo';
$this->assertFalse($this->...
Test Invalid Data
public function testShortNameInvalidatesForm()
{
$this->_data['name'] = 'Bo';
$this->assertFalse($this->...
Test Invalid Data
public function testShortNameInvalidatesForm()
{
$this->_data['name'] = 'Bo';
$this->assertFalse($this->...
Test Invalid Data
public function testShortNameInvalidatesForm()
{
$this->_data['name'] = 'Bo';
$this->assertFalse($this->...
Test Invalid Data
public function testShortNameInvalidatesForm()
{
$this->_data['name'] = 'Bo';
$this->assertFalse($this->...
PHPUnit Green, my Favorite Color!
Zend Form - Pros
● Object oriented
● Easy input validation
● Easy input filtering
● Markup generation
● Reusable
● Easy to...
Zend Form - Cons
● Learning curve
● Custom layouts can be challenging
● Default markup blows isn't my favorite
Wrapping Up
● Zend Form can save you from form hell
● Powerful in MVC
● Very simple to use outside of MVC
● Easy to test!
Questions?
Resources
● Zend_Form Quickstart
● http://bit.ly/ba8fr0
● Rob Allen's talk, “Working with Zend_Form”
● http://akrabat.com/...
Thanks!
Rate this talk: http://joind.in/2388
jeremy@jeremykendall.net
@JeremyKendall
http://jeremykendall.net
Upcoming SlideShare
Loading in …5
×

Zend_Form to the Rescue - A Brief Introduction to Zend_Form

5,770 views
5,628 views

Published on

Published in: Technology
1 Comment
2 Likes
Statistics
Notes
  • ritakoneh@hotmail.co.uk
    Hello My New friend
    My name is rita i saw your profile at(www.slideshare.net) and i love it i think we can click so please i will like you to email me back through my email address thus: so that i can told you more about me and give you my sweet picture so that you can know me will ok.
    Awaiting to see your lovely reply soonest.
    Miss rita ritakoneh@hotmail.co.uk
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total views
5,770
On SlideShare
0
From Embeds
0
Number of Embeds
14
Actions
Shares
0
Downloads
41
Comments
1
Likes
2
Embeds 0
No embeds

No notes for slide

Zend_Form to the Rescue - A Brief Introduction to Zend_Form

  1. 1. Zend Form to the Rescue! A Brief Introduction to Zend_Form
  2. 2. About Me Jeremy Kendall PHP Developer since 2001 Organizer Memphis PHP (MemphisPHP.org) Contributor to FRAPI project (getFRAPI.com) jeremy@jeremykendall.net @JeremyKendall http://jeremykendall.net
  3. 3. Forms in General ● Ubiquitous ● Tedious ● Challenging to get right ● Security risk ● Primary job responsibility
  4. 4. Typical Form Requirements ● Collect data ● Filter input ● Validate input ● Display validation messages ● Include default data (ex. List of US States) ● Pre-populate fields (for edit/update operations) ● Should be easy to test ● . . . and more.
  5. 5. Typical PHP Form ● Tons of markup ● Tons of code ● Confusing conditionals ● Client side validation likely ● Server side validation? ● Requires two scripts: form & processor ● Not at all easy to test ● I could go on and on . . .
  6. 6. Zend Form to the Rescue! ● Introduced in ZF 1.5, early 2008 ● Generates markup ● Filters and validates user input ● Displays validation advice ● Object oriented, easily extended ● Completely customizable ● Can be used apart from ZF MVC ● Easy to test
  7. 7. Standard Form Elements ● Button ● Captcha ● Checkbox ● File ● Hidden ● Hash ● Image ● MultiCheckbox ● MultiSelect ● Password ● Radio ● Reset ● Select ● Text ● TextArea
  8. 8. Standard Filter Classes ● Alnum ● Alpha ● Basename ● Boolean ● HtmlEntities ● StringToLower ● StringToUpper ● StringTrim ● And many more . . .
  9. 9. Standard Validation Classes ● Alnum ● Alpha ● Barcode ● Between ● Callback ● CreditCard ● Date ● Db ● RecordExists ● NoRecordExists ● Digits ● EmailAddress ● File ● Float ● GreaterThan ● Hex ● Hostname ● Iban ● Identical ● And many more . . .
  10. 10. Simple Contact Form <?php class Application_Form_Contact extends Zend_Form { public function init() { // Form elements and such will go here } }
  11. 11. Simple Contact Form <?php class Application_Form_Contact extends Zend_Form { public function init() { // Form elements and such will go here } }
  12. 12. Simple Contact Form <?php class Application_Form_Contact extends Zend_Form { public function init() { // Form elements and such will go here } }
  13. 13. Name Element $name = new Zend_Form_Element_Text('name'); $name->setLabel('Your name'); $name->setRequired(true); $name->addValidators(array( new Zend_Validate_Regex('/^[- a-z]+$/i'), new Zend_Validate_StringLength(array('min' => 5)) )); $this->addElement($name);
  14. 14. Name Element $name = new Zend_Form_Element_Text('name'); $name->setLabel('Your name'); $name->setRequired(true); $name->addValidators(array( new Zend_Validate_Regex('/^[- a-z]+$/i'), new Zend_Validate_StringLength(array('min' => 5)) )); $this->addElement($name);
  15. 15. Name Element $name = new Zend_Form_Element_Text('name'); $name->setLabel('Your name'); $name->setRequired(true); $name->addValidators(array( new Zend_Validate_Regex('/^[- a-z]+$/i'), new Zend_Validate_StringLength(array('min' => 5)) )); $this->addElement($name);
  16. 16. Name Element $name = new Zend_Form_Element_Text('name'); $name->setLabel('Your name'); $name->setRequired(true); $name->addValidators(array( new Zend_Validate_Regex('/^[- a-z]+$/i'), new Zend_Validate_StringLength(array('min' => 5)) )); $this->addElement($name);
  17. 17. Name Element $name = new Zend_Form_Element_Text('name'); $name->setLabel('Your name'); $name->setRequired(true); $name->addValidators(array( new Zend_Validate_Regex('/^[- a-z]+$/i'), new Zend_Validate_StringLength(array('min' => 5)) )); $this->addElement($name);
  18. 18. Name Element $name = new Zend_Form_Element_Text('name'); $name->setLabel('Your name'); $name->setRequired(true); $name->addValidators(array( new Zend_Validate_Regex('/^[- a-z]+$/i'), new Zend_Validate_StringLength(array('min' => 5)) )); $this->addElement($name);
  19. 19. Email Element $email = new Zend_Form_Element_Text('email'); $email->setLabel('Email Address'); $email->setRequired(true); $email->addValidators(array( new Zend_Validate_EmailAddress(), new Zend_Validate_StringLength(array('min' => 6)) )); $this->addElement($email);
  20. 20. Email Element $email = new Zend_Form_Element_Text('email'); $email->setLabel('Email Address'); $email->setRequired(true); $email->addValidators(array( new Zend_Validate_EmailAddress(), new Zend_Validate_StringLength(array('min' => 6)) )); $this->addElement($email);
  21. 21. Message Element $message = new Zend_Form_Element_Textarea('message'); $message->setLabel('Whatcha got to say?'); $message->setRequired(true); $message->setAttrib('cols', 40); $message->setAttrib('rows', 20); $this->addElement($message);
  22. 22. Message Element $message = new Zend_Form_Element_Textarea('message'); $message->setLabel('Whatcha got to say?'); $message->setRequired(true); $message->setAttrib('cols', 40); $message->setAttrib('rows', 20); $this->addElement($message);
  23. 23. Submit Element $submit = new Zend_Form_Element_Submit('submit'); $submit->setLabel('Make contact!'); $submit->setIgnore(true); $this->addElement($submit);
  24. 24. Submit Element $submit = new Zend_Form_Element_Submit('submit'); $submit->setLabel('Make contact!'); $submit->setIgnore(true); $this->addElement($submit);
  25. 25. Add Filters to All Elements $this->setElementFilters(array( new Zend_Filter_StringTrim(), new Zend_Filter_StripTags() ));
  26. 26. MVC Action public function indexAction() { $form = new Application_Form_Contact(); $this->view->form = $form; if (!$this->getRequest()->isPost()) { return; } if (!$form->isValid($_POST)) { return; } // Send email, persist data, etc. }
  27. 27. MVC Action public function indexAction() { $form = new Application_Form_Contact(); $this->view->form = $form; if (!$this->getRequest()->isPost()) { return; } if (!$form->isValid($_POST)) { return; } // Send email, persist data, etc. }
  28. 28. MVC Action public function indexAction() { $form = new Application_Form_Contact(); $this->view->form = $form; if (!$this->getRequest()->isPost()) { return; } if (!$form->isValid($_POST)) { return; } // Send email, persist data, etc. }
  29. 29. MVC Action public function indexAction() { $form = new Application_Form_Contact(); $this->view->form = $form; if (!$this->getRequest()->isPost()) { return; } if (!$form->isValid($_POST)) { return; } // Send email, persist data, etc. }
  30. 30. MVC Action public function indexAction() { $form = new Application_Form_Contact(); $this->view->form = $form; if (!$this->getRequest()->isPost()) { return; } if (!$form->isValid($_POST)) { return; } // Send email, persist data, etc. }
  31. 31. MVC Action public function indexAction() { $form = new Application_Form_Contact(); $this->view->form = $form; if (!$this->getRequest()->isPost()) { return; } if (!$form->isValid($_POST)) { return; } // Send email, persist data, etc.// Send email, persist data, etc. }
  32. 32. View <?php echo $this->form; ?>
  33. 33. Default Markup <form enctype="application/x-www-form-urlencoded" action="" method="post"> <dl class="zend_form"> <dt id="name-label"> <label for="name" class="required">Your name</label> </dt> <dd id="name-element"> <input type="text" name="name" id="name" value=""> </dd> . . . </dl> </form>
  34. 34. What does it look like?
  35. 35. How about with errors?
  36. 36. Can I use Zend Form by itself?
  37. 37. Standalone - library/base.php <?php // Ensure library/ is on include_path set_include_path(implode(PATH_SEPARATOR, array( dirname(__FILE__), get_include_path(), ))); require_once dirname(__FILE__) . '/Zend/Loader/Autoloader.php'; $autoloader = Zend_Loader_Autoloader::getInstance(); $autoloader->registerNamespace('Application_'); $view = new Zend_View();
  38. 38. Standalone - library/base.php <?php // Ensure library/ is on include_path set_include_path(implode(PATH_SEPARATOR, array( dirname(__FILE__), get_include_path(), ))); require_once dirname(__FILE__) . '/Zend/Loader/Autoloader.php'; $autoloader = Zend_Loader_Autoloader::getInstance(); $autoloader->registerNamespace('Application_'); $view = new Zend_View();
  39. 39. Standalone - library/base.php <?php // Ensure library/ is on include_path set_include_path(implode(PATH_SEPARATOR, array( dirname(__FILE__), get_include_path(), ))); require_once dirname(__FILE__) . '/Zend/Loader/Autoloader.php'; $autoloader = Zend_Loader_Autoloader::getInstance(); $autoloader->registerNamespace('Application_'); $view = new Zend_View();
  40. 40. Standalone - library/base.php <?php // Ensure library/ is on include_path set_include_path(implode(PATH_SEPARATOR, array( dirname(__FILE__), get_include_path(), ))); require_once dirname(__FILE__) . '/Zend/Loader/Autoloader.php'; $autoloader = Zend_Loader_Autoloader::getInstance(); $autoloader->registerNamespace('Application_'); $view = new Zend_View();
  41. 41. Standalone - library/base.php <?php // Ensure library/ is on include_path set_include_path(implode(PATH_SEPARATOR, array( dirname(__FILE__), get_include_path(), ))); require_once dirname(__FILE__) . '/Zend/Loader/Autoloader.php'; $autoloader = Zend_Loader_Autoloader::getInstance(); $autoloader->registerNamespace('Application_'); $view = new Zend_View();
  42. 42. Standalone – form script <?php require_once dirname(__FILE__) . '/library/base.php'; $form = new Application_Form_Contact(); if (strtolower($_SERVER['REQUEST_METHOD']) == 'get' || !$form->isValid($_POST)) { ?> <!-- Header file might go here --> <?php echo $form->render($view) ?> <!-- Footer file might go here --> <?php } elseif ($form->isValid($_POST)) { // Form valid, persist data, send email, etc. }
  43. 43. Standalone – form script <?php require_once dirname(__FILE__) . '/library/base.php'; $form = new Application_Form_Contact(); if (strtolower($_SERVER['REQUEST_METHOD']) == 'get' || !$form->isValid($_POST)) { ?> <!-- Header file might go here --> <?php echo $form->render($view) ?> <!-- Footer file might go here --> <?php } elseif ($form->isValid($_POST)) { // Form valid, persist data, send email, etc. }
  44. 44. Standalone – form script <?php require_once dirname(__FILE__) . '/library/base.php'; $form = new Application_Form_Contact(); if (strtolower($_SERVER['REQUEST_METHOD']) == 'get' || !$form->isValid($_POST)) { ?> <!-- Header file might go here --> <?php echo $form->render($view) ?> <!-- Footer file might go here --> <?php } elseif (s$form->isValid($_POST)) { // Form valid, persist data, send email, etc. }
  45. 45. Standalone – form script <?php require_once dirname(__FILE__) . '/library/base.php'; $form = new Application_Form_Contact(); if (strtolower($_SERVER['REQUEST_METHOD']) == 'get' || !$form->isValid($_POST)) { ?> <!-- Header file might go here --> <?php echo $form->render($view) ?> <!-- Footer file might go here --> <?php } elseif (strtolower($form->isValid($_POST)) { // Form valid, persist data, send email, etc. }
  46. 46. Standalone – form script <?php require_once dirname(__FILE__) . '/library/base.php'; $form = new Application_Form_Contact(); if (strtolower($_SERVER['REQUEST_METHOD']) == 'get' || !$form->isValid($_POST)) { ?> <!-- Header file might go here --> <?php echo $form->render($view) ?> <!-- Footer file might go here --> <?php } elseif ($form->isValid($_POST)) { // Form valid, persist data, send email, etc. }
  47. 47. Standalone – form script <?php require_once dirname(__FILE__) . '/library/base.php'; $form = new Application_Form_Contact(); if (strtolower($_SERVER['REQUEST_METHOD']) == 'get' || strtolower($_SERVER['REQUEST_METHOD']) == 'post' && !$form->isValid($_POST)) { ?> <!-- Header file might go here --> <?php echo $form->render($view) ?> <!-- Footer file might go here --> <?php } elseif ($form->isValid($_POST)) { // Form valid, persist data, send email, etc. }
  48. 48. Test time! <?php /** * ContactFormTest */ class ContactFormTest extends PHPUnit_Framework_TestCase { // Setup, teardown, and tests . . . }
  49. 49. Setting up our test public function setUp() { parent::setUp(); $this->_form = new Application_Form_Contact(); $this->_data = array( 'name' => 'Jeremy Kendall', 'email' => 'jeremy@jeremykendall.net', 'message' => 'Your slides are really, really ugly.' ); }
  50. 50. Setting up our test public function setUp() { parent::setUp(); $this->_form = new Application_Form_Contact(); $this->_data = array( 'name' => 'Jeremy Kendall', 'email' => 'jeremy@jeremykendall.net', 'message' => 'Your slides are really, really ugly.' ); }
  51. 51. Setting up our test public function setUp() { parent::setUp(); $this->_form = new Application_Form_Contact(); $this->_data = array( 'name' => 'Jeremy Kendall', 'email' => 'jeremy@jeremykendall.net', 'message' => 'Your slides are really, really ugly.' ); }
  52. 52. Test Valid Data public function testValidDataPassesValidation() { $this->assertTrue($this->_form->isValid($this->_data)); }
  53. 53. Test Invalid Data public function testShortNameInvalidatesForm() { $this->_data['name'] = 'Bo'; $this->assertFalse($this->_form->isValid($this->_data)); $messages = $this->_form->getMessages(); $this->assertArrayHasKey('name', $messages); $this->assertArrayHasKey( 'stringLengthTooShort', $messages['name'] );
  54. 54. Test Invalid Data public function testShortNameInvalidatesForm() { $this->_data['name'] = 'Bo'; $this->assertFalse($this->_form->isValid($this->_data)); $messages = $this->_form->getMessages(); $this->assertArrayHasKey('name', $messages); $this->assertArrayHasKey( 'stringLengthTooShort', $messages['name'] );
  55. 55. Test Invalid Data public function testShortNameInvalidatesForm() { $this->_data['name'] = 'Bo'; $this->assertFalse($this->_form->isValid($this->_data)); $messages = $this->_form->getMessages(); $this->assertArrayHasKey('name', $messages); $this->assertArrayHasKey( 'stringLengthTooShort', $messages['name'] );
  56. 56. Test Invalid Data public function testShortNameInvalidatesForm() { $this->_data['name'] = 'Bo'; $this->assertFalse($this->_form->isValid($this->_data)); $messages = $this->_form->getMessages(); $this->assertArrayHasKey('name', $messages); $this->assertArrayHasKey( 'stringLengthTooShort', $messages['name'] );
  57. 57. Test Invalid Data public function testShortNameInvalidatesForm() { $this->_data['name'] = 'Bo'; $this->assertFalse($this->_form->isValid($this->_data)); $messages = $this->_form->getMessages(); $this->assertArrayHasKey('name', $messages); $this->assertArrayHasKey( 'stringLengthTooShort', $messages['name'] );
  58. 58. PHPUnit Green, my Favorite Color!
  59. 59. Zend Form - Pros ● Object oriented ● Easy input validation ● Easy input filtering ● Markup generation ● Reusable ● Easy to test
  60. 60. Zend Form - Cons ● Learning curve ● Custom layouts can be challenging ● Default markup blows isn't my favorite
  61. 61. Wrapping Up ● Zend Form can save you from form hell ● Powerful in MVC ● Very simple to use outside of MVC ● Easy to test!
  62. 62. Questions?
  63. 63. Resources ● Zend_Form Quickstart ● http://bit.ly/ba8fr0 ● Rob Allen's talk, “Working with Zend_Form” ● http://akrabat.com/talks/ ● Zend_Form_Element_Multi – Tips and Tricks ● http://bit.ly/bEZl37
  64. 64. Thanks! Rate this talk: http://joind.in/2388 jeremy@jeremykendall.net @JeremyKendall http://jeremykendall.net

×