1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
|
<?xml version="1.0" encoding="UTF-8"?>
<!-- Reviewed: no -->
<sect1 id="zend.form.advanced">
<title>Advanced Zend_Form Usage</title>
<para>
<classname>Zend_Form</classname> has a wealth of functionality, much of it aimed
at experienced developers. This chapter aims to document some of this
functionality with examples and use cases.
</para>
<sect2 id="zend.form.advanced.arrayNotation">
<title>Array Notation</title>
<para>
Many experienced web developers like to group related form elements
using array notation in the element names. For example, if you have
two addresses you wish to capture, a shipping and a billing address,
you may have identical elements; by grouping them in an array, you
can ensure they are captured separately. Take the following form,
for example:
</para>
<programlisting language="html"><![CDATA[
<form>
<fieldset>
<legend>Shipping Address</legend>
<dl>
<dt><label for="recipient">Ship to:</label></dt>
<dd><input name="recipient" type="text" value="" /></dd>
<dt><label for="address">Address:</label></dt>
<dd><input name="address" type="text" value="" /></dd>
<dt><label for="municipality">City:</label></dt>
<dd><input name="municipality" type="text" value="" /></dd>
<dt><label for="province">State:</label></dt>
<dd><input name="province" type="text" value="" /></dd>
<dt><label for="postal">Postal Code:</label></dt>
<dd><input name="postal" type="text" value="" /></dd>
</dl>
</fieldset>
<fieldset>
<legend>Billing Address</legend>
<dl>
<dt><label for="payer">Bill To:</label></dt>
<dd><input name="payer" type="text" value="" /></dd>
<dt><label for="address">Address:</label></dt>
<dd><input name="address" type="text" value="" /></dd>
<dt><label for="municipality">City:</label></dt>
<dd><input name="municipality" type="text" value="" /></dd>
<dt><label for="province">State:</label></dt>
<dd><input name="province" type="text" value="" /></dd>
<dt><label for="postal">Postal Code:</label></dt>
<dd><input name="postal" type="text" value="" /></dd>
</dl>
</fieldset>
<dl>
<dt><label for="terms">I agree to the Terms of Service</label></dt>
<dd><input name="terms" type="checkbox" value="" /></dd>
<dt></dt>
<dd><input name="save" type="submit" value="Save" /></dd>
</dl>
</form>
]]></programlisting>
<para>
In this example, the billing and shipping address contain some
identical fields, which means one would overwrite the other. We can
solve this solution using array notation:
</para>
<programlisting language="html"><![CDATA[
<form>
<fieldset>
<legend>Shipping Address</legend>
<dl>
<dt><label for="shipping-recipient">Ship to:</label></dt>
<dd><input name="shipping[recipient]" id="shipping-recipient"
type="text" value="" /></dd>
<dt><label for="shipping-address">Address:</label></dt>
<dd><input name="shipping[address]" id="shipping-address"
type="text" value="" /></dd>
<dt><label for="shipping-municipality">City:</label></dt>
<dd><input name="shipping[municipality]" id="shipping-municipality"
type="text" value="" /></dd>
<dt><label for="shipping-province">State:</label></dt>
<dd><input name="shipping[province]" id="shipping-province"
type="text" value="" /></dd>
<dt><label for="shipping-postal">Postal Code:</label></dt>
<dd><input name="shipping[postal]" id="shipping-postal"
type="text" value="" /></dd>
</dl>
</fieldset>
<fieldset>
<legend>Billing Address</legend>
<dl>
<dt><label for="billing-payer">Bill To:</label></dt>
<dd><input name="billing[payer]" id="billing-payer"
type="text" value="" /></dd>
<dt><label for="billing-address">Address:</label></dt>
<dd><input name="billing[address]" id="billing-address"
type="text" value="" /></dd>
<dt><label for="billing-municipality">City:</label></dt>
<dd><input name="billing[municipality]" id="billing-municipality"
type="text" value="" /></dd>
<dt><label for="billing-province">State:</label></dt>
<dd><input name="billing[province]" id="billing-province"
type="text" value="" /></dd>
<dt><label for="billing-postal">Postal Code:</label></dt>
<dd><input name="billing[postal]" id="billing-postal"
type="text" value="" /></dd>
</dl>
</fieldset>
<dl>
<dt><label for="terms">I agree to the Terms of Service</label></dt>
<dd><input name="terms" type="checkbox" value="" /></dd>
<dt></dt>
<dd><input name="save" type="submit" value="Save" /></dd>
</dl>
</form>
]]></programlisting>
<para>
In the above sample, we now get separate addresses. In the submitted
form, we'll now have three elements, the 'save' element for the
submit, and then two arrays, 'shipping' and 'billing', each with
keys for their various elements.
</para>
<para>
<classname>Zend_Form</classname> attempts to automate this process with its
<link linkend="zend.form.forms.subforms">sub forms</link>. By
default, sub forms render using the array notation as shown in the
previous <acronym>HTML</acronym> form listing, complete with ids. The array name is
based on the sub form name, with the keys based on the elements
contained in the sub form. Sub forms may be nested arbitrarily deep,
and this will create nested arrays to reflect the structure.
Additionally, the various validation routines in
<classname>Zend_Form</classname> honor the array structure, ensuring that your
form validates correctly, no matter how arbitrarily deep you nest
your sub forms. You need do nothing to benefit from this; this
behaviour is enabled by default.
</para>
<para>
Additionally, there are facilities that allow you to turn on array
notation conditionally, as well as specify the specific array to
which an element or collection belongs:
</para>
<itemizedlist>
<listitem>
<para>
<methodname>Zend_Form::setIsArray($flag)</methodname>: By setting the
flag <constant>TRUE</constant>, you can indicate that an entire form should be
treated as an array. By default, the form's name will be
used as the name of the array, unless
<methodname>setElementsBelongTo()</methodname> has been called. If the
form has no specified name, or if
<methodname>setElementsBelongTo()</methodname> has not been set, this
flag will be ignored (as there is no array name to which
the elements may belong).
</para>
<para>
You may determine if a form is being treated as an array
using the <methodname>isArray()</methodname> accessor.
</para>
</listitem>
<listitem>
<para>
<methodname>Zend_Form::setElementsBelongTo($array)</methodname>:
Using this method, you can specify the name of an array to
which all elements of the form belong. You can determine the
name using the <methodname>getElementsBelongTo()</methodname> accessor.
</para>
</listitem>
</itemizedlist>
<para>
Additionally, on the element level, you can specify individual
elements may belong to particular arrays using
<methodname>Zend_Form_Element::setBelongsTo()</methodname> method.
To discover what this value is -- whether set explicitly or
implicitly via the form -- you may use the
<methodname>getBelongsTo()</methodname> accessor.
</para>
</sect2>
<sect2 id="zend.form.advanced.multiPage">
<title>Multi-Page Forms</title>
<para>
Currently, Multi-Page forms are not officially supported in
<classname>Zend_Form</classname>; however, most support for implementing them
is available and can be utilized with a little extra tooling.
</para>
<para>
The key to creating a multi-page form is to utilize sub forms, but
to display only one such sub form per page. This allows you to
submit a single sub form at a time and validate it, but not process
the form until all sub forms are complete.
</para>
<example id="zend.form.advanced.multiPage.registration">
<title>Registration Form Example</title>
<para>
Let's use a registration form as an example. For our purposes,
we want to capture the desired username and password on the
first page, then the user's metadata -- given name, family name,
and location -- and finally allow them to decide what mailing
lists, if any, they wish to subscribe to.
</para>
<para>
First, let's create our own form, and define several sub forms
within it:
</para>
<programlisting language="php"><![CDATA[
class My_Form_Registration extends Zend_Form
{
public function init()
{
// Create user sub form: username and password
$user = new Zend_Form_SubForm();
$user->addElements(array(
new Zend_Form_Element_Text('username', array(
'required' => true,
'label' => 'Username:',
'filters' => array('StringTrim', 'StringToLower'),
'validators' => array(
'Alnum',
array('Regex',
false,
array('/^[a-z][a-z0-9]{2,}$/'))
)
)),
new Zend_Form_Element_Password('password', array(
'required' => true,
'label' => 'Password:',
'filters' => array('StringTrim'),
'validators' => array(
'NotEmpty',
array('StringLength', false, array(6))
)
)),
));
// Create demographics sub form: given name, family name, and
// location
$demog = new Zend_Form_SubForm();
$demog->addElements(array(
new Zend_Form_Element_Text('givenName', array(
'required' => true,
'label' => 'Given (First) Name:',
'filters' => array('StringTrim'),
'validators' => array(
array('Regex',
false,
array('/^[a-z][a-z0-9., \'-]{2,}$/i'))
)
)),
new Zend_Form_Element_Text('familyName', array(
'required' => true,
'label' => 'Family (Last) Name:',
'filters' => array('StringTrim'),
'validators' => array(
array('Regex',
false,
array('/^[a-z][a-z0-9., \'-]{2,}$/i'))
)
)),
new Zend_Form_Element_Text('location', array(
'required' => true,
'label' => 'Your Location:',
'filters' => array('StringTrim'),
'validators' => array(
array('StringLength', false, array(2))
)
)),
));
// Create mailing lists sub form
$listOptions = array(
'none' => 'No lists, please',
'fw-general' => 'Zend Framework General List',
'fw-mvc' => 'Zend Framework MVC List',
'fw-auth' => 'Zend Framwork Authentication and ACL List',
'fw-services' => 'Zend Framework Web Services List',
);
$lists = new Zend_Form_SubForm();
$lists->addElements(array(
new Zend_Form_Element_MultiCheckbox('subscriptions', array(
'label' =>
'Which lists would you like to subscribe to?',
'multiOptions' => $listOptions,
'required' => true,
'filters' => array('StringTrim'),
'validators' => array(
array('InArray',
false,
array(array_keys($listOptions)))
)
)),
));
// Attach sub forms to main form
$this->addSubForms(array(
'user' => $user,
'demog' => $demog,
'lists' => $lists
));
}
}
]]></programlisting>
<para>
Note that there are no submit buttons, and that we have done
nothing with the sub form decorators -- which means that by
default they will be displayed as fieldsets. We will need to be
able to override these as we display each individual sub form,
and add in submit buttons so we can actually process them --
which will also require action and method properties. Let's add
some scaffolding to our class to provide that information:
</para>
<programlisting language="php"><![CDATA[
class My_Form_Registration extends Zend_Form
{
// ...
/**
* Prepare a sub form for display
*
* @param string|Zend_Form_SubForm $spec
* @return Zend_Form_SubForm
*/
public function prepareSubForm($spec)
{
if (is_string($spec)) {
$subForm = $this->{$spec};
} elseif ($spec instanceof Zend_Form_SubForm) {
$subForm = $spec;
} else {
throw new Exception('Invalid argument passed to ' .
__FUNCTION__ . '()');
}
$this->setSubFormDecorators($subForm)
->addSubmitButton($subForm)
->addSubFormActions($subForm);
return $subForm;
}
/**
* Add form decorators to an individual sub form
*
* @param Zend_Form_SubForm $subForm
* @return My_Form_Registration
*/
public function setSubFormDecorators(Zend_Form_SubForm $subForm)
{
$subForm->setDecorators(array(
'FormElements',
array('HtmlTag', array('tag' => 'dl',
'class' => 'zend_form')),
'Form',
));
return $this;
}
/**
* Add a submit button to an individual sub form
*
* @param Zend_Form_SubForm $subForm
* @return My_Form_Registration
*/
public function addSubmitButton(Zend_Form_SubForm $subForm)
{
$subForm->addElement(new Zend_Form_Element_Submit(
'save',
array(
'label' => 'Save and continue',
'required' => false,
'ignore' => true,
)
));
return $this;
}
/**
* Add action and method to sub form
*
* @param Zend_Form_SubForm $subForm
* @return My_Form_Registration
*/
public function addSubFormActions(Zend_Form_SubForm $subForm)
{
$subForm->setAction('/registration/process')
->setMethod('post');
return $this;
}
}
]]></programlisting>
<para>
Next, we need to add some scaffolding in our action controller,
and have several considerations. First, we need to make sure we
persist form data between requests, so that we can determine
when to quit. Second, we need some logic to determine what form
segments have already been submitted, and what sub form to
display based on that information. We'll use
<classname>Zend_Session_Namespace</classname> to persist data, which will
also help us answer the question of which form to submit.
</para>
<para>
Let's create our controller, and add a method for retrieving a
form instance:
</para>
<programlisting language="php"><![CDATA[
class RegistrationController extends Zend_Controller_Action
{
protected $_form;
public function getForm()
{
if (null === $this->_form) {
$this->_form = new My_Form_Registration();
}
return $this->_form;
}
}
]]></programlisting>
<para>
Now, let's add some functionality for determining which form to
display. Basically, until the entire form is considered valid,
we need to continue displaying form segments. Additionally, we
likely want to make sure they're in a particular order: user,
demog, and then lists. We can determine what data has been
submitted by checking our session namespace for particular keys
representing each subform.
</para>
<programlisting language="php"><![CDATA[
class RegistrationController extends Zend_Controller_Action
{
// ...
protected $_namespace = 'RegistrationController';
protected $_session;
/**
* Get the session namespace we're using
*
* @return Zend_Session_Namespace
*/
public function getSessionNamespace()
{
if (null === $this->_session) {
$this->_session =
new Zend_Session_Namespace($this->_namespace);
}
return $this->_session;
}
/**
* Get a list of forms already stored in the session
*
* @return array
*/
public function getStoredForms()
{
$stored = array();
foreach ($this->getSessionNamespace() as $key => $value) {
$stored[] = $key;
}
return $stored;
}
/**
* Get list of all subforms available
*
* @return array
*/
public function getPotentialForms()
{
return array_keys($this->getForm()->getSubForms());
}
/**
* What sub form was submitted?
*
* @return false|Zend_Form_SubForm
*/
public function getCurrentSubForm()
{
$request = $this->getRequest();
if (!$request->isPost()) {
return false;
}
foreach ($this->getPotentialForms() as $name) {
if ($data = $request->getPost($name, false)) {
if (is_array($data)) {
return $this->getForm()->getSubForm($name);
break;
}
}
}
return false;
}
/**
* Get the next sub form to display
*
* @return Zend_Form_SubForm|false
*/
public function getNextSubForm()
{
$storedForms = $this->getStoredForms();
$potentialForms = $this->getPotentialForms();
foreach ($potentialForms as $name) {
if (!in_array($name, $storedForms)) {
return $this->getForm()->getSubForm($name);
}
}
return false;
}
}
]]></programlisting>
<para>
The above methods allow us to use notations such as "<command>$subForm =
$this->getCurrentSubForm();</command>" to retrieve the current
sub form for validation, or "<command>$next =
$this->getNextSubForm();</command>" to get the next one to
display.
</para>
<para>
Now, let's figure out how to process and display the various sub
forms. We can use <methodname>getCurrentSubForm()</methodname> to determine
if any sub forms have been submitted (<constant>FALSE</constant> return values
indicate none have been displayed or submitted), and
<methodname>getNextSubForm()</methodname> to retrieve a form to display. We
can then use the form's <methodname>prepareSubForm()</methodname> method to
ensure the form is ready for display.
</para>
<para>
When we have a form submission, we can validate the sub form,
and then check to see if the entire form is now valid. To do
these tasks, we'll need additional methods that ensure that
submitted data is added to the session, and that when validating
the form entire, we validate against all segments from the
session:
</para>
<programlisting language="php"><![CDATA[
class RegistrationController extends Zend_Controller_Action
{
// ...
/**
* Is the sub form valid?
*
* @param Zend_Form_SubForm $subForm
* @param array $data
* @return bool
*/
public function subFormIsValid(Zend_Form_SubForm $subForm,
array $data)
{
$name = $subForm->getName();
if ($subForm->isValid($data)) {
$this->getSessionNamespace()->$name = $subForm->getValues();
return true;
}
return false;
}
/**
* Is the full form valid?
*
* @return bool
*/
public function formIsValid()
{
$data = array();
foreach ($this->getSessionNamespace() as $key => $info) {
$data[$key] = $info;
}
return $this->getForm()->isValid($data);
}
}
]]></programlisting>
<para>
Now that we have the legwork out of the way, let's build the
actions for this controller. We'll need a landing page for the
form, and then a 'process' action for processing the form.
</para>
<programlisting language="php"><![CDATA[
class RegistrationController extends Zend_Controller_Action
{
// ...
public function indexAction()
{
// Either re-display the current page, or grab the "next"
// (first) sub form
if (!$form = $this->getCurrentSubForm()) {
$form = $this->getNextSubForm();
}
$this->view->form = $this->getForm()->prepareSubForm($form);
}
public function processAction()
{
if (!$form = $this->getCurrentSubForm()) {
return $this->_forward('index');
}
if (!$this->subFormIsValid($form,
$this->getRequest()->getPost())) {
$this->view->form = $this->getForm()->prepareSubForm($form);
return $this->render('index');
}
if (!$this->formIsValid()) {
$form = $this->getNextSubForm();
$this->view->form = $this->getForm()->prepareSubForm($form);
return $this->render('index');
}
// Valid form!
// Render information in a verification page
$this->view->info = $this->getSessionNamespace();
$this->render('verification');
}
}
]]></programlisting>
<para>
As you'll notice, the actual code for processing the form is
relatively simple. We check to see if we have a current sub form
submission, and if not, we go back to the landing page. If we do
have a sub form, we attempt to validate it, redisplaying it if
it fails. If the sub form is valid, we then check to see if the
form is valid, which would indicate we're done; if not, we
display the next form segment. Finally, we display a
verification page with the contents of the session.
</para>
<para>
The view scripts are very simple:
</para>
<programlisting language="php"><![CDATA[
<?php // registration/index.phtml ?>
<h2>Registration</h2>
<?php echo $this->form ?>
<?php // registration/verification.phtml ?>
<h2>Thank you for registering!</h2>
<p>
Here is the information you provided:
</p>
<?
// Have to do this construct due to how items are stored in session
// namespaces
foreach ($this->info as $info):
foreach ($info as $form => $data): ?>
<h4><?php echo ucfirst($form) ?>:</h4>
<dl>
<?php foreach ($data as $key => $value): ?>
<dt><?php echo ucfirst($key) ?></dt>
<?php if (is_array($value)):
foreach ($value as $label => $val): ?>
<dd><?php echo $val ?></dd>
<?php endforeach;
else: ?>
<dd><?php echo $this->escape($value) ?></dd>
<?php endif;
endforeach; ?>
</dl>
<?php endforeach;
endforeach ?>
]]></programlisting>
<para>
Upcoming releases of Zend Framework will include components to
make multi page forms simpler by abstracting the session and
ordering logic. In the meantime, the above example should serve
as a reasonable guideline on how to accomplish this task for
your site.
</para>
</example>
</sect2>
</sect1>
<!--
vim:se ts=4 sw=4 et:
-->
|