Zend_Form-QuickStart.xml 21 KB

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