Zend_Form-Advanced.xml 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. <sect1 id="zend.form.advanced">
  2. <title>Zend_Form 的高级用法 </title>
  3. <para>
  4. <code>Zend_Form</code> 有丰富的函数,其中许多面向有经验的开发者。这一章打算用例子和用例来介绍这些函数。
  5. </para>
  6. <sect2 id="zend.form.advanced.arrayNotation">
  7. <title> 数组符号(Notation)</title>
  8. <para>
  9. 许多有经验的 web 开发者喜欢在元素名上用数组符号把相关的表单元素组成组。例如,如果有两个地址在表单上,一个邮寄地址和一个帐单地址,你可能会有相同的元素,通过把它们用数组组成组,你可以确保它们能分别被抓取。用下面的表单做个例子:
  10. </para>
  11. <programlisting role="html"><![CDATA[
  12. <form>
  13. <fieldset>
  14. <legend>Shipping Address</legend>
  15. <dl>
  16. <dt><label for="recipient">Ship to:</label></dt>
  17. <dd><input name="recipient" type="text" value="" /></dd>
  18. <dt><label for="address">Address:</label></dt>
  19. <dd><input name="address" type="text" value="" /></dd>
  20. <dt><label for="municipality">City:</label></dt>
  21. <dd><input name="municipality" type="text" value="" /></dd>
  22. <dt><label for="province">State:</label></dt>
  23. <dd><input name="province" type="text" value="" /></dd>
  24. <dt><label for="postal">Postal Code:</label></dt>
  25. <dd><input name="postal" type="text" value="" /></dd>
  26. </dl>
  27. </fieldset>
  28. <fieldset>
  29. <legend>Billing Address</legend>
  30. <dl>
  31. <dt><label for="payer">Bill To:</label></dt>
  32. <dd><input name="payer" type="text" value="" /></dd>
  33. <dt><label for="address">Address:</label></dt>
  34. <dd><input name="address" type="text" value="" /></dd>
  35. <dt><label for="municipality">City:</label></dt>
  36. <dd><input name="municipality" type="text" value="" /></dd>
  37. <dt><label for="province">State:</label></dt>
  38. <dd><input name="province" type="text" value="" /></dd>
  39. <dt><label for="postal">Postal Code:</label></dt>
  40. <dd><input name="postal" type="text" value="" /></dd>
  41. </dl>
  42. </fieldset>
  43. <dl>
  44. <dt><label for="terms">I agree to the Terms of Service</label></dt>
  45. <dd><input name="terms" type="checkbox" value="" /></dd>
  46. <dt></dt>
  47. <dd><input name="save" type="submit" value="Save" /></dd>
  48. </dl>
  49. </form>
  50. ]]></programlisting>
  51. <para>
  52. 在本例中,帐单地址和邮寄地址包含一些相同的字段,这意味着一个可能会覆盖另一个。我们可以用数组符号来解决这个问题:
  53. </para>
  54. <programlisting role="html"><![CDATA[
  55. <form>
  56. <fieldset>
  57. <legend>Shipping Address</legend>
  58. <dl>
  59. <dt><label for="shipping-recipient">Ship to:</label></dt>
  60. <dd><input name="shipping[recipient]" id="shipping-recipient"
  61. type="text" value="" /></dd>
  62. <dt><label for="shipping-address">Address:</label></dt>
  63. <dd><input name="shipping[address]" id="shipping-address"
  64. type="text" value="" /></dd>
  65. <dt><label for="shipping-municipality">City:</label></dt>
  66. <dd><input name="shipping[municipality]" id="shipping-municipality"
  67. type="text" value="" /></dd>
  68. <dt><label for="shipping-province">State:</label></dt>
  69. <dd><input name="shipping[province]" id="shipping-province"
  70. type="text" value="" /></dd>
  71. <dt><label for="shipping-postal">Postal Code:</label></dt>
  72. <dd><input name="shipping[postal]" id="shipping-postal"
  73. type="text" value="" /></dd>
  74. </dl>
  75. </fieldset>
  76. <fieldset>
  77. <legend>Billing Address</legend>
  78. <dl>
  79. <dt><label for="billing-payer">Bill To:</label></dt>
  80. <dd><input name="billing[payer]" id="billing-payer"
  81. type="text" value="" /></dd>
  82. <dt><label for="billing-address">Address:</label></dt>
  83. <dd><input name="billing[address]" id="billing-address"
  84. type="text" value="" /></dd>
  85. <dt><label for="billing-municipality">City:</label></dt>
  86. <dd><input name="billing[municipality]" id="billing-municipality"
  87. type="text" value="" /></dd>
  88. <dt><label for="billing-province">State:</label></dt>
  89. <dd><input name="billing[province]" id="billing-province"
  90. type="text" value="" /></dd>
  91. <dt><label for="billing-postal">Postal Code:</label></dt>
  92. <dd><input name="billing[postal]" id="billing-postal"
  93. type="text" value="" /></dd>
  94. </dl>
  95. </fieldset>
  96. <dl>
  97. <dt><label for="terms">I agree to the Terms of Service</label></dt>
  98. <dd><input name="terms" type="checkbox" value="" /></dd>
  99. <dt></dt>
  100. <dd><input name="save" type="submit" value="Save" /></dd>
  101. </dl>
  102. </form>
  103. ]]></programlisting>
  104. <para>
  105. 在上例中,我们有了两个单独的地址。在提交的表单,我们有三个元素,'save' 元素表示提交,和两个数组 'shipping' 和 'billing',每个都有键对应它们的元素。
  106. </para>
  107. <para>
  108. <code>Zend_Form</code> 尝试用 <link linkend="zend.form.forms.subforms">sub forms</link> 自动完成这个过程。缺省地,子表单用前面 HTML 表单列表包括 ids 所示的数组符号来解析,数组名基于子表单名,键基于包含在子表单中的元素。子表单的嵌套有任意深度,这将生成嵌套数组来反映它的结构。另外,<code>Zend_Form</code> 中不同的校验程序遵循数组结构,不论子表单的嵌套有多深,都确保表单校验正确。你不需要做任何事情来获得这些好处,缺省是打开(enabled)的。
  109. </para>
  110. <para>
  111. 另外,有工具让你有条件地打开数组符号,也可以指定特定的数组给元素和集合所属的(子表单或表单):
  112. </para>
  113. <itemizedlist>
  114. <listitem>
  115. <para>
  116. <code>Zend_Form::setIsArray($flag)</code>:通过设置标志为 true,你可以让整个表单当作数组。缺省地,表单名将是数组名,除非调用了 <code>setElementsBelongTo()</code>。如果表单没有名称,或如果 <code>setElementsBelongTo()</code> 没有设置,这个标志将被忽略(因为没有数组名给元素所属于的表单)。
  117. </para>
  118. <para>
  119. 你可以用 <code>isArray()</code> 访问器来决定一个表单是否被当作数组。
  120. </para>
  121. </listitem>
  122. <listitem><para>
  123. <code>Zend_Form::setElementsBelongTo($array)</code>:用这个方法,你可以指定数组名给元素所属的表单,也可以使用 <code>getElementsBelongTo()</code> 访问器来确定(获得?)它的名字。
  124. </para></listitem>
  125. </itemizedlist>
  126. <para>
  127. 另外,在元素一级,你可以用 <code>Zend_Form_Element::setBelongsTo()</code> 方法指定可能属于特定的数组的独立的元素。
  128. 为了找出这个值是什么 - 是否显式或隐式地通过表单 - 可以用 <code>getBelongsTo()</code> 访问器来做。
  129. </para>
  130. </sect2>
  131. <sect2 id="zend.form.advanced.multiPage">
  132. <title> 多页表单 </title>
  133. <para>
  134. 目前,<code>Zend_Form</code> 没有正式支持多页表单,然而,可以用一些额外的工具来实现。
  135. </para>
  136. <para>
  137. 生成多页表单的关键是利用子表单,但每个页面只显示一个子表单。这让你一次提交一个单个的表单并校验它,直到所有表单都提交了才处理。
  138. </para>
  139. <example id="zend.form.advanced.multiPage.registration">
  140. <title> 注册表单示例 </title>
  141. <para>
  142. 让我们用注册表单作为例子,我们的意图是在第一页上读取期望的用户名和密码,还有用户的元数据 -- 用户的名字、姓和地点 -- 最后让他们决定使用哪个邮件列表(如果有的话)。
  143. </para>
  144. <para>
  145. 首先,来生成表单,并在里面定义一些子表单:
  146. </para>
  147. <programlisting role="php"><![CDATA[<?php
  148. class My_Form_Registration extends Zend_Form
  149. {
  150. public function init()
  151. {
  152. // Create user sub form: username and password
  153. $user = new Zend_Form_SubForm();
  154. $user->addElements(array(
  155. new Zend_Form_Element_Text('username', array(
  156. 'required' => true,
  157. 'label' => 'Username:',
  158. 'filters' => array('StringTrim', 'StringToLower'),
  159. 'validators' => array(
  160. 'Alnum',
  161. array('Regex', false, array('/^[a-z][a-z0-9]{2,}$/'))
  162. )
  163. )),
  164. new Zend_Form_Element_Password('password', array(
  165. 'required' => true,
  166. 'label' => 'Password:',
  167. 'filters' => array('StringTrim'),
  168. 'validators' => array(
  169. 'NotEmpty',
  170. array('StringLength', false, array(6))
  171. )
  172. )),
  173. ));
  174. // Create demographics sub form: given name, family name, and location
  175. $demog = new Zend_Form_SubForm();
  176. $demog->addElements(array(
  177. new Zend_Form_Element_Text('givenName', array(
  178. 'required' => true,
  179. 'label' => 'Given (First) Name:',
  180. 'filters' => array('StringTrim'),
  181. 'validators' => array(
  182. array('Regex', false, array('/^[a-z][a-z0-9., \'-]{2,}$/i'))
  183. )
  184. )),
  185. new Zend_Form_Element_Text('familyName', array(
  186. 'required' => true,
  187. 'label' => 'Family (Last) Name:',
  188. 'filters' => array('StringTrim'),
  189. 'validators' => array(
  190. array('Regex', false, array('/^[a-z][a-z0-9., \'-]{2,}$/i'))
  191. )
  192. )),
  193. new Zend_Form_Element_Text('location', array(
  194. 'required' => true,
  195. 'label' => 'Your Location:',
  196. 'filters' => array('StringTrim'),
  197. 'validators' => array(
  198. array('StringLength', false, array(2))
  199. )
  200. )),
  201. ));
  202. // Create mailing lists sub form
  203. $listOptions = array(
  204. 'none' => 'No lists, please',
  205. 'fw-general' => 'Zend Framework General List',
  206. 'fw-mvc' => 'Zend Framework MVC List',
  207. 'fw-auth' => 'Zend Framwork Authentication and ACL List',
  208. 'fw-services' => 'Zend Framework Web Services List',
  209. );
  210. $lists = new Zend_Form_SubForm();
  211. $lists->addElements(array(
  212. new Zend_Form_Element_MultiCheckbox('subscriptions', array(
  213. 'label' => 'Which lists would you like to subscribe to?',
  214. 'multiOptions' => $listOptions,
  215. 'required' => true,
  216. 'filters' => array('StringTrim'),
  217. 'validators' => array(
  218. array('InArray', false, array(array_keys($listOptions)))
  219. )
  220. )),
  221. ));
  222. // Attach sub forms to main form
  223. $this->addSubForms(array(
  224. 'user' => $user,
  225. 'demog' => $demog,
  226. 'lists' => $lists
  227. ));
  228. }
  229. }
  230. ]]></programlisting>
  231. <para>
  232. 注意还没有提交按钮,而起我们对子表单的装饰器也没有做任何事情 -- 意思是缺省地他们作为字段(fieldsets)显示。我们将能够 override 这些因为我们显示每个独立的子表单,并加入提交按钮这样我们就可以处理它们了 -- 也要求有动作和方法(注:这里的方法是 'post' 或 'get')属性。来给我们的类添砖加瓦让它提供那些信息:
  233. </para>
  234. <programlisting role="php"><![CDATA[
  235. class My_Form_Registration extends Zend_Form
  236. {
  237. // ...
  238. /**
  239. * Prepare a sub form for display
  240. *
  241. * @param string|Zend_Form_SubForm $spec
  242. * @return Zend_Form_SubForm
  243. */
  244. public function prepareSubForm($spec)
  245. {
  246. if (is_string($spec)) {
  247. $subForm = $this->{$spec};
  248. } elseif ($spec instanceof Zend_Form_SubForm) {
  249. $subForm = $spec;
  250. } else {
  251. throw new Exception('Invalid argument passed to ' . __FUNCTION__ . '()');
  252. }
  253. $this->setSubFormDecorators($subForm)
  254. ->addSubmitButton($subForm)
  255. ->addSubFormActions($subForm);
  256. return $subForm;
  257. }
  258. /**
  259. * Add form decorators to an individual sub form
  260. *
  261. * @param Zend_Form_SubForm $subForm
  262. * @return My_Form_Registration
  263. */
  264. public function setSubFormDecorators(Zend_Form_SubForm $subForm)
  265. {
  266. $subForm->setDecorators(array(
  267. 'FormElements',
  268. array('HtmlTag', array('tag' => 'dl', 'class' => 'zend_form')),
  269. 'Form',
  270. ));
  271. return $this;
  272. }
  273. /**
  274. * Add a submit button to an individual sub form
  275. *
  276. * @param Zend_Form_SubForm $subForm
  277. * @return My_Form_Registration
  278. */
  279. public function addSubmitButton(Zend_Form_SubForm $subForm)
  280. {
  281. $subForm->addElement(new Zend_Form_Element_Submit(
  282. 'save',
  283. array(
  284. 'label' => 'Save and continue',
  285. 'required' => false,
  286. 'ignore' => true,
  287. )
  288. ));
  289. return $this;
  290. }
  291. /**
  292. * Add action and method to sub form
  293. *
  294. * @param Zend_Form_SubForm $subForm
  295. * @return My_Form_Registration
  296. */
  297. public function addSubFormActions(Zend_Form_SubForm $subForm)
  298. {
  299. $subForm->setAction('/registration/process')
  300. ->setMethod('post');
  301. return $this;
  302. }
  303. }
  304. ]]></programlisting>
  305. <para>
  306. 接着,我们也需要为动作控制器添加一些辅助东西,并有若干考虑。首先,我们需要确保在请求之间保持表单数据,这样可以确定何时退出。第二,我们需要一些逻辑来确定表单的哪部分已经提交,哪个子表单需要基于这些信息来显示。我们使用 <code>Zend_Session_Namespace</code> 来保持数据,它也会告诉我们提交哪个表单。
  307. </para>
  308. <para>
  309. 让我们来创建控制器,并添加用于获取表单实例的方法:
  310. </para>
  311. <programlisting role="php"><![CDATA[<?php
  312. class RegistrationController extends Zend_Controller_Action
  313. {
  314. protected $_form;
  315. public function getForm()
  316. {
  317. if (null === $this->_form) {
  318. require_once 'My/Form/Registration.php';
  319. $this->_form = new My_Form_Registration();
  320. }
  321. return $this->_form;
  322. }
  323. }
  324. ]]></programlisting>
  325. <para>
  326. 现在,添加一些函数来确定显示哪个表单。基本上,直到整个表单被认为有效,我们才需要继续显示表单片段。另外,我们可能想确保它们是按一定的顺序:用户、demog 和 列表。我们在可以通过检查出现在每个子表单上的特定键的会话命名空间确定哪个数据被提交。
  327. </para>
  328. <programlisting role="php"><![CDATA[
  329. class RegistrationController extends Zend_Controller_Action
  330. {
  331. // ...
  332. protected $_namespace = 'RegistrationController';
  333. protected $_session;
  334. /**
  335. * Get the session namespace we're using
  336. *
  337. * @return Zend_Session_Namespace
  338. */
  339. public function getSessionNamespace()
  340. {
  341. if (null === $this->_session) {
  342. require_once 'Zend/Session/Namespace.php';
  343. $this->_session = new Zend_Session_Namespace($this->_namespace);
  344. }
  345. return $this->_session;
  346. }
  347. /**
  348. * Get a list of forms already stored in the session
  349. *
  350. * @return array
  351. */
  352. public function getStoredForms()
  353. {
  354. $stored = array();
  355. foreach ($this->getSessionNamespace() as $key => $value) {
  356. $stored[] = $key;
  357. }
  358. return $stored;
  359. }
  360. /**
  361. * Get list of all subforms available
  362. *
  363. * @return array
  364. */
  365. public function getPotentialForms()
  366. {
  367. return array_keys($this->getForm()->getSubForms());
  368. }
  369. /**
  370. * What sub form was submitted?
  371. *
  372. * @return false|Zend_Form_SubForm
  373. */
  374. public function getCurrentSubForm()
  375. {
  376. $request = $this->getRequest();
  377. if (!$request->isPost()) {
  378. return false;
  379. }
  380. foreach ($this->getPotentialForms() as $name) {
  381. if ($data = $request->getPost($name, false)) {
  382. if (is_array($data)) {
  383. return $this->getForm()->getSubForm($name);
  384. break;
  385. }
  386. }
  387. }
  388. return false;
  389. }
  390. /**
  391. * Get the next sub form to display
  392. *
  393. * @return Zend_Form_SubForm|false
  394. */
  395. public function getNextSubForm()
  396. {
  397. $storedForms = $this->getStoredForms();
  398. $potentialForms = $this->getPotentialForms();
  399. foreach ($potentialForms as $name) {
  400. if (!in_array($name, $storedForms)) {
  401. return $this->getForm()->getSubForm($name);
  402. }
  403. }
  404. return false;
  405. }
  406. }
  407. ]]></programlisting>
  408. <para>
  409. 上述方法让我们使用符合如 "<code>$subForm = $this-&gt;getCurrentSubForm();</code>" 来读取当前子表单来校验,或者 "<code>$next = $this-&gt;getNextSubForm();</code>" 来获得下一个来显示。
  410. </para>
  411. <para>
  412. 现在,让我们看一下如何处理和显示不同的子表单。我们可以使用 <code>getCurrentSubForm()</code> 来确定表单是否提交(返回 false 值表示没有显示或提交),并且用 <code>getNextSubForm()</code> 来获取表单来显示。我们还可以用表单的 <code>prepareSubForm()</code> 方法来确保表单已准备好显示。
  413. </para>
  414. <para>
  415. 当我们收到表单提交,可以校验子表单并接着检查是否整个表单有效。为完成这些任务,我们需要另外的方法确保提交的数据添加到会话和什么时候校验整个表单,我们依靠从会话来的所有片段(segments)来校验:
  416. </para>
  417. <programlisting role="php"><![CDATA[<?php
  418. class My_Form_Registration extends Zend_Form
  419. {
  420. // ...
  421. /**
  422. * Is the sub form valid?
  423. *
  424. * @param Zend_Form_SubForm $subForm
  425. * @param array $data
  426. * @return bool
  427. */
  428. public function subFormIsValid(Zend_Form_SubForm $subForm, array $data)
  429. {
  430. $name = $subForm->getName();
  431. if ($subForm->isValid($data)) {
  432. $this->getSessionNamespace()->$name = $subForm->getValues();
  433. return true;
  434. }
  435. return false;
  436. }
  437. /**
  438. * Is the full form valid?
  439. *
  440. * @return bool
  441. */
  442. public function formIsValid()
  443. {
  444. $data = array();
  445. foreach ($this->getSessionNamespace() as $key => $info) {
  446. $data[$key] = $info;
  447. }
  448. return $this->getForm()->isValid($data);
  449. }
  450. }
  451. ]]></programlisting>
  452. <para>
  453. 八字已经画了一撇,让我们来为控制器构造一个动作。我们需要为表单做一个 landing 页面,接着'process' 动作来处理表单。
  454. </para>
  455. <programlisting role="php"><![CDATA[<?php
  456. class RegistrationController extends Zend_Controller_Action
  457. {
  458. // ...
  459. public function indexAction()
  460. {
  461. // Either re-display the current page, or grab the "next" (first)
  462. // sub form
  463. if (!$form = $this->getCurrentSubForm()) {
  464. $form = $this->getNextSubForm();
  465. }
  466. $this->view->form = $this->getForm()->prepareSubForm($form);
  467. }
  468. public function processAction()
  469. {
  470. if (!$form = $this->getCurrentSubForm()) {
  471. return $this->_forward('index');
  472. }
  473. if (!$this->subFormIsValid($form, $this->getRequest()->getPost())) {
  474. $this->view->form = $this->getForm()->prepareSubForm($form);
  475. return $this->render('index');
  476. }
  477. if (!$this->formIsValid()) {
  478. $form = $this->getNextSubForm();
  479. $this->view->form = $this->getForm()->prepareSubForm($form);
  480. return $this->render('index');
  481. }
  482. // Valid form!
  483. // Render information in a verification page
  484. $this->view->info = $this->getSessionNamespace();
  485. $this->render('verification');
  486. }
  487. }
  488. ]]></programlisting>
  489. <para>
  490. 正如你注意到的,处理表单的代码相当简单。我们检查是否有一个子表单提交,如果没有,就回到 landing 页面。如果我们确实有一个子表单,就尝试校验它,如果失败,重新显示。如果子表单有效,那么我们就检查表单是否有效,它将指示我们是否完成,如果没有,我们就显示下一个表单片段。最后,我们显示一个确认过的带有会话内容的页面。
  491. </para>
  492. <para>
  493. The view scripts are very simple:
  494. </para>
  495. <programlisting role="php"><![CDATA[
  496. <? // registration/index.phtml ?>
  497. <h2>Registration</h2>
  498. <?= $this->form ?>
  499. <? // registration/verification.phtml ?>
  500. <h2>Thank you for registering!</h2>
  501. <p>
  502. 这里是你所提供的信息:
  503. </p>
  504. <?
  505. // Have to do this construct due to how items are stored in session namespaces
  506. foreach ($this->info as $info):
  507. foreach ($info as $form => $data): ?>
  508. <h4><?= ucfirst($form) ?>:</h4>
  509. <dl>
  510. <? foreach ($data as $key => $value): ?>
  511. <dt><?= ucfirst($key) ?></dt>
  512. <? if (is_array($value)):
  513. foreach ($value as $label => $val): ?>
  514. <dd><?= $val ?></dd>
  515. <? endforeach;
  516. else: ?>
  517. <dd><?= $this->escape($value) ?></dd>
  518. <? endif;
  519. endforeach; ?>
  520. </dl>
  521. <? endforeach;
  522. endforeach ?>
  523. ]]></programlisting>
  524. <para>
  525. Zend Framework 的下次发行将通过抽象会话和顺序逻辑来提供制作多页面表单的组件。在这期间,上述例子对如何为你的站点生成多页面是个合理的指南。
  526. </para>
  527. </example>
  528. </sect2>
  529. </sect1>
  530. <!--
  531. vim:se ts=4 sw=4 et:
  532. -->