Zend_Form-QuickStart.xml 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!-- Reviewed: no -->
  3. <sect1 id="zend.form.quickstart">
  4. <title>Zend_Form Quick Start</title>
  5. <para>
  6. This quick start guide covers the basics of creating,
  7. validating, and rendering forms with <classname>Zend_Form</classname>.
  8. </para>
  9. <sect2 id="zend.form.quickstart.create">
  10. <title>Create a form object</title>
  11. <para>
  12. Creating a form object is very simple: simply instantiate
  13. <classname>Zend_Form</classname>:
  14. </para>
  15. <programlisting language="php"><![CDATA[
  16. $form = new Zend_Form;
  17. ]]></programlisting>
  18. <para>
  19. For advanced use cases, you may want to create a
  20. <classname>Zend_Form</classname> subclass, but for simple forms, you can
  21. create a form programmatically using a <classname>Zend_Form</classname>
  22. object.
  23. </para>
  24. <para>
  25. If you wish to specify the form action and method (always good
  26. ideas), you can do so with the <methodname>setAction()</methodname> and
  27. <methodname>setMethod()</methodname> accessors:
  28. </para>
  29. <programlisting language="php"><![CDATA[
  30. $form->setAction('/resource/process')
  31. ->setMethod('post');
  32. ]]></programlisting>
  33. <para>
  34. The above code sets the form action to the partial <acronym>URL</acronym>
  35. "/resource/process" and the form method to <acronym>HTTP</acronym> POST. This will be
  36. reflected during final rendering.
  37. </para>
  38. <para>
  39. You can set additional HTML attributes for the
  40. <code>&lt;form&gt;</code> tag by using the setAttrib() or
  41. setAttribs() methods. For instance, if you wish to set the id, set
  42. the "id" attribute:
  43. </para>
  44. <programlisting language="php"><![CDATA[
  45. $form->setAttrib('id', 'login');
  46. ]]></programlisting>
  47. </sect2>
  48. <sect2 id="zend.form.quickstart.elements">
  49. <title>Add elements to the form</title>
  50. <para>
  51. A form is nothing without its elements. <classname>Zend_Form</classname>
  52. ships with some default elements that render <acronym>XHTML</acronym> via
  53. <classname>Zend_View</classname> helpers. These are as follows:
  54. </para>
  55. <itemizedlist>
  56. <listitem><para>
  57. button
  58. </para></listitem>
  59. <listitem><para>
  60. checkbox (or many checkboxes at once with multiCheckbox)
  61. </para></listitem>
  62. <listitem><para>
  63. hidden
  64. </para></listitem>
  65. <listitem><para>
  66. image
  67. </para></listitem>
  68. <listitem><para>
  69. password
  70. </para></listitem>
  71. <listitem><para>
  72. radio
  73. </para></listitem>
  74. <listitem><para>
  75. reset
  76. </para></listitem>
  77. <listitem><para>
  78. select (both regular and multi-select types)
  79. </para></listitem>
  80. <listitem><para>
  81. submit
  82. </para></listitem>
  83. <listitem><para>
  84. text
  85. </para></listitem>
  86. <listitem><para>
  87. textarea
  88. </para></listitem>
  89. </itemizedlist>
  90. <para>
  91. You have two options for adding elements to a form: you can
  92. instantiate concrete elements and pass in these objects, or you can
  93. pass in simply the element type and have <classname>Zend_Form</classname>
  94. instantiate an object of the correct type for you.
  95. </para>
  96. <para>
  97. Some examples:
  98. </para>
  99. <programlisting language="php"><![CDATA[
  100. // Instantiating an element and passing to the form object:
  101. $form->addElement(new Zend_Form_Element_Text('username'));
  102. // Passing a form element type to the form object:
  103. $form->addElement('text', 'username');
  104. ]]></programlisting>
  105. <para>
  106. By default, these do not have any validators or filters. This means
  107. you will need to configure your elements with at least validators,
  108. and potentially filters. You can either do this (a) before you pass
  109. the element to the form, (b) via configuration options passed in
  110. when creating an element via <classname>Zend_Form</classname>, or (c) by
  111. pulling the element from the form object and configuring it after
  112. the fact.
  113. </para>
  114. <para>
  115. Let's first look at creating validators for a concrete element
  116. instance. You can either pass in <classname>Zend_Validate_*</classname>
  117. objects, or the name of a validator to utilize:
  118. </para>
  119. <programlisting language="php"><![CDATA[
  120. $username = new Zend_Form_Element_Text('username');
  121. // Passing a Zend_Validate_* object:
  122. $username->addValidator(new Zend_Validate_Alnum());
  123. // Passing a validator name:
  124. $username->addValidator('alnum');
  125. ]]></programlisting>
  126. <para>
  127. When using this second option, you can pass constructor arguments in an array as the
  128. third parameter if the validator can accept tem:
  129. </para>
  130. <programlisting language="php"><![CDATA[
  131. // Pass a pattern
  132. $username->addValidator('regex', false, array('/^[a-z]/i'));
  133. ]]></programlisting>
  134. <para>
  135. (The second parameter is used to indicate whether or not failure of
  136. this validator should prevent later validators from running; by
  137. default, this is <constant>FALSE</constant>.)
  138. </para>
  139. <para>
  140. You may also wish to specify an element as required. This can be
  141. done using an accessor or passing an option when creating
  142. the element. In the former case:
  143. </para>
  144. <programlisting language="php"><![CDATA[
  145. // Make this element required:
  146. $username->setRequired(true);
  147. ]]></programlisting>
  148. <para>
  149. When an element is required, a 'NotEmpty' validator is added to the
  150. top of the validator chain, ensuring that the element has a value
  151. when required.
  152. </para>
  153. <para>
  154. Filters are registered in basically the same way as validators. For
  155. illustration purposes, let's add a filter to lowercase the final
  156. value:
  157. </para>
  158. <programlisting language="php"><![CDATA[
  159. $username->addFilter('StringtoLower');
  160. ]]></programlisting>
  161. <para>
  162. The final element setup might look like this:
  163. </para>
  164. <programlisting language="php"><![CDATA[
  165. $username->addValidator('alnum')
  166. ->addValidator('regex', false, array('/^[a-z]/'))
  167. ->setRequired(true)
  168. ->addFilter('StringToLower');
  169. // or, more compactly:
  170. $username->addValidators(array('alnum',
  171. array('regex', false, '/^[a-z]/i')
  172. ))
  173. ->setRequired(true)
  174. ->addFilters(array('StringToLower'));
  175. ]]></programlisting>
  176. <para>
  177. Simple as this is, repeating it this for every element in a form
  178. can be a bit tedious. Let's try option (b) from above. When we
  179. create a new element using <methodname>Zend_Form::addElement()</methodname> as
  180. a factory, we can optionally pass in configuration options. These
  181. can include validators and filters. To do all of the
  182. above implicitly, try the following:
  183. </para>
  184. <programlisting language="php"><![CDATA[
  185. $form->addElement('text', 'username', array(
  186. 'validators' => array(
  187. 'alnum',
  188. array('regex', false, '/^[a-z]/i')
  189. ),
  190. 'required' => true,
  191. 'filters' => array('StringToLower'),
  192. ));
  193. ]]></programlisting>
  194. <note><para>
  195. If you find you are setting up elements using the same options in
  196. many locations, you may want to consider creating your own
  197. <classname>Zend_Form_Element</classname> subclass and utilizing that class
  198. instead; this will save you typing in the long-run.
  199. </para></note>
  200. </sect2>
  201. <sect2 id="zend.form.quickstart.render">
  202. <title>Render a form</title>
  203. <para>
  204. Rendering a form is simple. Most elements use a
  205. <classname>Zend_View</classname> helper to render themselves, and thus need a
  206. view object in order to render. Other than that, you have two
  207. options: use the form's render() method, or simply echo it.
  208. </para>
  209. <programlisting language="php"><![CDATA[
  210. // Explicitly calling render(), and passing an optional view object:
  211. echo $form->render($view);
  212. // Assuming a view object has been previously set via setView():
  213. echo $form;
  214. ]]></programlisting>
  215. <para>
  216. By default, <classname>Zend_Form</classname> and
  217. <classname>Zend_Form_Element</classname> will attempt to use the view object
  218. initialized in the <code>ViewRenderer</code>, which means you won't
  219. need to set the view manually when using the Zend Framework <acronym>MVC</acronym>.
  220. To render a form in a view, you simply have to do the following:
  221. </para>
  222. <programlisting language="php"><![CDATA[
  223. <?php echo $this->form ?>
  224. ]]></programlisting>
  225. <para>
  226. Under the hood, <classname>Zend_Form</classname> uses "decorators" to perform
  227. rendering. These decorators can replace content, append content, or
  228. prepend content, and can fully introspect the element passed
  229. to them. As a result, you can combine multiple decorators to
  230. achieve custom effects. By default, <classname>Zend_Form_Element</classname>
  231. actually combines four decorators to achieve its output; setup
  232. looks something like this:
  233. </para>
  234. <programlisting language="php"><![CDATA[
  235. $element->addDecorators(array(
  236. 'ViewHelper',
  237. 'Errors',
  238. array('HtmlTag', array('tag' => 'dd')),
  239. array('Label', array('tag' => 'dt')),
  240. ));
  241. ]]></programlisting>
  242. <para>
  243. (Where &lt;HELPERNAME&gt; is the name of a view helper to use, and varies
  244. based on the element.)
  245. </para>
  246. <para>
  247. The above creates output like the following:
  248. </para>
  249. <programlisting language="html"><![CDATA[
  250. <dt><label for="username" class="required">Username</dt>
  251. <dd>
  252. <input type="text" name="username" value="123-abc" />
  253. <ul class="errors">
  254. <li>'123-abc' has not only alphabetic and digit characters</li>
  255. <li>'123-abc' does not match against pattern '/^[a-z]/i'</li>
  256. </ul>
  257. </dd>
  258. ]]></programlisting>
  259. <para>
  260. (Albeit not with the same formatting.)
  261. </para>
  262. <para>
  263. You can change the decorators used by an element if you wish to
  264. have different output; see the section on decorators for more
  265. information.
  266. </para>
  267. <para>
  268. The form itself simply loops through the elements, and dresses them
  269. in an HTML <code>&lt;form&gt;</code>. The action and method you
  270. provided when setting up the form are provided to the
  271. <code>&lt;form&gt;</code> tag, as are any attributes you set via
  272. <methodname>setAttribs()</methodname> and family.
  273. </para>
  274. <para>
  275. Elements are looped either in the order in which they were
  276. registered, or, if your element contains an order attribute, that
  277. order will be used. You can set an element's order using:
  278. </para>
  279. <programlisting language="php"><![CDATA[
  280. $element->setOrder(10);
  281. ]]></programlisting>
  282. <para>
  283. Or, when creating an element, by passing it as an option:
  284. </para>
  285. <programlisting language="php"><![CDATA[
  286. $form->addElement('text', 'username', array('order' => 10));
  287. ]]></programlisting>
  288. </sect2>
  289. <sect2 id="zend.form.quickstart.validate">
  290. <title>Check if a form is valid</title>
  291. <para>
  292. After a form is submitted, you will need to check and see if it
  293. passes validations. Each element is checked against the data
  294. provided; if a key matching the element name is not present, and
  295. the item is marked as required, validations are run with a <constant>NULL</constant>
  296. value.
  297. </para>
  298. <para>
  299. Where does the data come from? You can use <varname>$_POST</varname> or
  300. <varname>$_GET</varname>, or any other data source you might have at hand
  301. (web service requests, for instance):
  302. </para>
  303. <programlisting language="php"><![CDATA[
  304. if ($form->isValid($_POST)) {
  305. // success!
  306. } else {
  307. // failure!
  308. }
  309. ]]></programlisting>
  310. <para>
  311. With <acronym>AJAX</acronym> requests, you can sometimes get away with validating
  312. a single element, or groups of elements.
  313. <methodname>isValidPartial()</methodname> will validate a partial form. Unlike
  314. <methodname>isValid()</methodname>, however, if a particular key is not
  315. present, it will not run validations for that particular element:
  316. </para>
  317. <programlisting language="php"><![CDATA[
  318. if ($form->isValidPartial($_POST)) {
  319. // elements present all passed validations
  320. } else {
  321. // one or more elements tested failed validations
  322. }
  323. ]]></programlisting>
  324. <para>
  325. An additional method, <methodname>processAjax()</methodname>, can be used
  326. for validating partial forms. Unlike <methodname>isValidPartial()</methodname>,
  327. it returns a <acronym>JSON</acronym>-formatted string containing error messages on
  328. failure.
  329. </para>
  330. <para>
  331. Assuming your validations have passed, you can now fetch the
  332. filtered values:
  333. </para>
  334. <programlisting language="php"><![CDATA[
  335. $values = $form->getValues();
  336. ]]></programlisting>
  337. <para>
  338. If you need the unfiltered values at any point, use:
  339. </para>
  340. <programlisting language="php"><![CDATA[
  341. $unfiltered = $form->getUnfilteredValues();
  342. ]]></programlisting>
  343. <para>
  344. If you on the other hand need all the valid and filtered values of a partially valid form,
  345. you can call:
  346. </para>
  347. <programlisting language="php"><![CDATA[
  348. $values = $form->getValidValues($_POST);
  349. ]]></programlisting>
  350. </sect2>
  351. <sect2 id="zend.form.quickstart.errorstatus">
  352. <title>Get error status</title>
  353. <para>
  354. Did your form have failed validations on submission? In most cases, you can simply
  355. render the form again, and errors will be displayed when using the
  356. default decorators:
  357. </para>
  358. <programlisting language="php"><![CDATA[
  359. if (!$form->isValid($_POST)) {
  360. echo $form;
  361. // or assign to the view object and render a view...
  362. $this->view->form = $form;
  363. return $this->render('form');
  364. }
  365. ]]></programlisting>
  366. <para>
  367. If you want to inspect the errors, you have two methods.
  368. <methodname>getErrors()</methodname> returns an associative array of element
  369. names / codes (where codes is an array of error codes).
  370. <methodname>getMessages()</methodname> returns an associative array of element
  371. names / messages (where messages is an associative array of error
  372. code / error message pairs). If a given element does not have any
  373. errors, it will not be included in the array.
  374. </para>
  375. </sect2>
  376. <sect2 id="zend.form.quickstart.puttingtogether">
  377. <title>Putting it together</title>
  378. <para>
  379. Let's build a simple login form. It will need elements
  380. representing:
  381. </para>
  382. <itemizedlist>
  383. <listitem><para>username</para></listitem>
  384. <listitem><para>password</para></listitem>
  385. <listitem><para>submit</para></listitem>
  386. </itemizedlist>
  387. <para>
  388. For our purposes, let's assume that a valid username should be
  389. alphanumeric characters only, start with a letter, have a minimum
  390. length of 6, and maximum length of 20; they will be normalized to
  391. lowercase. Passwords must be a minimum of 6 characters. We'll
  392. simply toss the submit value when done, so it can remain
  393. unvalidated.
  394. </para>
  395. <para>
  396. We'll use the power of <classname>Zend_Form</classname>'s configuration
  397. options to build the form:
  398. </para>
  399. <programlisting language="php"><![CDATA[
  400. $form = new Zend_Form();
  401. $form->setAction('/user/login')
  402. ->setMethod('post');
  403. // Create and configure username element:
  404. $username = $form->createElement('text', 'username');
  405. $username->addValidator('alnum')
  406. ->addValidator('regex', false, array('/^[a-z]+/'))
  407. ->addValidator('stringLength', false, array(6, 20))
  408. ->setRequired(true)
  409. ->addFilter('StringToLower');
  410. // Create and configure password element:
  411. $password = $form->createElement('password', 'password');
  412. $password->addValidator('StringLength', false, array(6))
  413. ->setRequired(true);
  414. // Add elements to form:
  415. $form->addElement($username)
  416. ->addElement($password)
  417. // use addElement() as a factory to create 'Login' button:
  418. ->addElement('submit', 'login', array('label' => 'Login'));
  419. ]]></programlisting>
  420. <para>
  421. Next, we'll create a controller for handling this:
  422. </para>
  423. <programlisting language="php"><![CDATA[
  424. class UserController extends Zend_Controller_Action
  425. {
  426. public function getForm()
  427. {
  428. // create form as above
  429. return $form;
  430. }
  431. public function indexAction()
  432. {
  433. // render user/form.phtml
  434. $this->view->form = $this->getForm();
  435. $this->render('form');
  436. }
  437. public function loginAction()
  438. {
  439. if (!$this->getRequest()->isPost()) {
  440. return $this->_forward('index');
  441. }
  442. $form = $this->getForm();
  443. if (!$form->isValid($_POST)) {
  444. // Failed validation; redisplay form
  445. $this->view->form = $form;
  446. return $this->render('form');
  447. }
  448. $values = $form->getValues();
  449. // now try and authenticate....
  450. }
  451. }
  452. ]]></programlisting>
  453. <para>
  454. And a view script for displaying the form:
  455. </para>
  456. <programlisting language="php"><![CDATA[
  457. <h2>Please login:</h2>
  458. <?php echo $this->form ?>
  459. ]]></programlisting>
  460. <para>
  461. As you'll note from the controller code, there's more work to do:
  462. while the submission may be valid, you may still need to do some authentication
  463. using <classname>Zend_Auth</classname> or another authorization mechanism.
  464. </para>
  465. </sect2>
  466. <sect2 id="zend.form.quickstart.config">
  467. <title>Using a Zend_Config Object</title>
  468. <para>
  469. All <classname>Zend_Form</classname> classes are configurable using
  470. <classname>Zend_Config</classname>; you can either pass a
  471. <classname>Zend_Config</classname> object to the constructor or pass it in
  472. with <methodname>setConfig()</methodname>. Let's look at how we might create the
  473. above form using an <acronym>INI</acronym> file. First, let's follow the
  474. recommendations, and place our configurations into sections
  475. reflecting the release location, and focus on the 'development'
  476. section. Next, we'll setup a section for the given controller
  477. ('user'), and a key for the form ('login'):
  478. </para>
  479. <programlisting language="ini"><![CDATA[
  480. [development]
  481. ; general form metainformation
  482. user.login.action = "/user/login"
  483. user.login.method = "post"
  484. ; username element
  485. user.login.elements.username.type = "text"
  486. user.login.elements.username.options.validators.alnum.validator = "alnum"
  487. user.login.elements.username.options.validators.regex.validator = "regex"
  488. user.login.elements.username.options.validators.regex.options.pattern = "/^[a-z]/i"
  489. user.login.elements.username.options.validators.strlen.validator = "StringLength"
  490. user.login.elements.username.options.validators.strlen.options.min = "6"
  491. user.login.elements.username.options.validators.strlen.options.max = "20"
  492. user.login.elements.username.options.required = true
  493. user.login.elements.username.options.filters.lower.filter = "StringToLower"
  494. ; password element
  495. user.login.elements.password.type = "password"
  496. user.login.elements.password.options.validators.strlen.validator = "StringLength"
  497. user.login.elements.password.options.validators.strlen.options.min = "6"
  498. user.login.elements.password.options.required = true
  499. ; submit element
  500. user.login.elements.submit.type = "submit"
  501. ]]></programlisting>
  502. <para>
  503. You would then pass this to the form constructor:
  504. </para>
  505. <programlisting language="php"><![CDATA[
  506. $config = new Zend_Config_Ini($configFile, 'development');
  507. $form = new Zend_Form($config->user->login);
  508. ]]></programlisting>
  509. <para>
  510. and the entire form will be defined.
  511. </para>
  512. </sect2>
  513. <sect2 id="zend.form.quickstart.conclusion">
  514. <title>Conclusion</title>
  515. <para>
  516. Hopefully with this little tutorial, you should now be well on your
  517. way to unlocking the power and flexibility of
  518. <classname>Zend_Form</classname>. Read on for more in-depth information!
  519. </para>
  520. </sect2>
  521. </sect1>
  522. <!--
  523. vim:se ts=4 sw=4 et:
  524. -->