10-Forms.txt 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193
  1. Chapter 10 - Forms
  2. ==================
  3. >**Caution**
  4. >This chapter describes the way forms were implemented in symfony 1.0. For
  5. compatibility reasons and because the admin generator feature still uses
  6. this system, this information is also valuable for symfony 1.1. However, if
  7. you start a new project with symfony 1.1, you should also read the "symfony
  8. Forms in Action" book for more information on the new forms framework.
  9. When writing templates, much of a developer's time is devoted to forms. Despite this, forms are generally poorly designed. Since much attention is required to deal with default values, formatting, validation, repopulation, and form handling in general, some developers tend to skim over some important details in the process. Accordingly, symfony devotes special attention to this topic. This chapter describes the tools that automate many of these requirements while speeding up forms development:
  10. * The form helpers provide a faster way to write form inputs in templates, especially for complex elements such as dates, drop-down lists, and rich text.
  11. * When a form is devoted to editing the properties of an object, the templating can be further accelerated by using object form helpers.
  12. * The YAML validation files facilitate form validation and repopulation.
  13. * Validators package the code required to validate input. Symfony bundles validators for the most common needs, and it is very easy to add custom validators.
  14. Form Helpers
  15. ------------
  16. In templates, HTML tags of form elements are very often mixed with PHP code. Form helpers in symfony aim to simplify this task and to avoid opening `<?php echo` tags repeatedly in the middle of `<input>` tags.
  17. ### Main Form Tag
  18. As explained in the previous chapter, you must use the `form_tag()` helper to create a form, since it transforms the action given as a parameter into a routed URL. The second argument can support additional options--for instance, to change the default `method`, change the default `enctype`, or specify other attributes. Listing 10-1 shows examples.
  19. Listing 10-1 - The `form_tag()` Helper
  20. [php]
  21. <?php echo form_tag('test/save') ?>
  22. => <form method="post" action="/path/to/save">
  23. <?php echo form_tag('test/save', 'method=get multipart=true class=simpleForm') ?>
  24. => <form method="get" enctype="multipart/form-data" class="simpleForm"action="/path/to/save">
  25. As there is no need for a closing form helper, you should use the HTML `</form>` tag, even if it doesn't look good in your source code.
  26. ### Standard Form Elements
  27. With form helpers, each element in a form is given an id attribute deduced from its name attribute by default. This is not the only useful convention. See Listing 10-2 for a full list of standard form helpers and their options.
  28. Listing 10-2 - Standard Form Helpers Syntax
  29. [php]
  30. // Text field (input)
  31. <?php echo input_tag('name', 'default value') ?>
  32. => <input type="text" name="name" id="name" value="default value" />
  33. // All form helpers accept an additional options parameter
  34. // It allows you to add custom attributes to the generated tag
  35. <?php echo input_tag('name', 'default value', 'maxlength=20') ?>
  36. => <input type="text" name="name" id="name" value="default value" maxlength="20" />
  37. // Long text field (text area)
  38. <?php echo textarea_tag('name', 'default content', 'size=10x20') ?>
  39. => <textarea name="name" id="name" cols="10" rows="20">
  40. default content
  41. </textarea>
  42. // Check box
  43. <?php echo checkbox_tag('single', 1, true) ?>
  44. <?php echo checkbox_tag('driverslicense', 'B', false) ?>
  45. => <input type="checkbox" name="single" id="single" value="1" checked="checked" />
  46. <input type="checkbox" name="driverslicense" id="driverslicense" value="B" />
  47. // Radio button
  48. <?php echo radiobutton_tag('status[]', 'value1', true) ?>
  49. <?php echo radiobutton_tag('status[]', 'value2', false) ?>
  50. => <input type="radio" name="status[]" id="status_value1" value="value1" checked="checked" />
  51. <input type="radio" name="status[]" id="status_value2" value="value2" />
  52. // Dropdown list (select)
  53. <?php echo select_tag('payment',
  54. '<option selected="selected">Visa</option>
  55. <option>Eurocard</option>
  56. <option>Mastercard</option>')
  57. ?>
  58. => <select name="payment" id="payment">
  59. <option selected="selected">Visa</option>
  60. <option>Eurocard</option>
  61. <option>Mastercard</option>
  62. </select>
  63. // List of options for a select tag
  64. <?php echo options_for_select(array('Visa', 'Eurocard', 'Mastercard'), 0) ?>
  65. => <option value="0" selected="selected">Visa</option>
  66. <option value="1">Eurocard</option>
  67. <option value="2">Mastercard</option>
  68. // Dropdown helper combined with a list of options
  69. <?php echo select_tag('payment', options_for_select(array(
  70. 'Visa',
  71. 'Eurocard',
  72. 'Mastercard'
  73. ), 0)) ?>
  74. => <select name="payment" id="payment">
  75. <option value="0" selected="selected">Visa</option>
  76. <option value="1">Eurocard</option>
  77. <option value="2">Mastercard</option>
  78. </select>
  79. // To specify option names, use an associative array
  80. <?php echo select_tag('name', options_for_select(array(
  81. 'Steve' => 'Steve',
  82. 'Bob' => 'Bob',
  83. 'Albert' => 'Albert',
  84. 'Ian' => 'Ian',
  85. 'Buck' => 'Buck'
  86. ), 'Ian')) ?>
  87. => <select name="name" id="name">
  88. <option value="Steve">Steve</option>
  89. <option value="Bob">Bob</option>
  90. <option value="Albert">Albert</option>
  91. <option value="Ian" selected="selected">Ian</option>
  92. <option value="Buck">Buck</option>
  93. </select>
  94. // Dropdown list with multiple selection (selected values can be an array)
  95. <?php echo select_tag('payment', options_for_select(
  96. array('Visa' => 'Visa', 'Eurocard' => 'Eurocard', 'Mastercard' => 'Mastercard'),
  97. array('Visa', 'Mastercard'),
  98. ), array('multiple' => true))) ?>
  99. => <select name="payment[]" id="payment" multiple="multiple">
  100. <option value="Visa" selected="selected">Visa</option>
  101. <option value="Eurocard">Eurocard</option>
  102. <option value="Mastercard">Mastercard</option>
  103. </select>
  104. // Drop-down list with multiple selection (selected values can be an array)
  105. <?php echo select_tag('payment', options_for_select(
  106. array('Visa' => 'Visa', 'Eurocard' => 'Eurocard', 'Mastercard' => 'Mastercard'),
  107. array('Visa', 'Mastercard')
  108. ), 'multiple=multiple') ?>
  109. => <select name="payment[]" id="payment" multiple="multiple">
  110. <option value="Visa" selected="selected">Visa</option>
  111. <option value="Eurocard">Eurocard</option>
  112. <option value="Mastercard" selected="selected">Mastercard</option>
  113. </select>
  114. // Upload file field
  115. <?php echo input_file_tag('name') ?>
  116. => <input type="file" name="name" id="name" value="" />
  117. // Password field
  118. <?php echo input_password_tag('name', 'value') ?>
  119. => <input type="password" name="name" id="name" value="value" />
  120. // Hidden field
  121. <?php echo input_hidden_tag('name', 'value') ?>
  122. => <input type="hidden" name="name" id="name" value="value" />
  123. // Submit button (as text)
  124. <?php echo submit_tag('Save') ?>
  125. => <input type="submit" name="submit" value="Save" />
  126. // Submit button (as image)
  127. <?php echo submit_image_tag('submit_img') ?>
  128. => <input type="image" name="submit" src="/images/submit_img.png" />
  129. The `submit_image_tag()` helper uses the same syntax and has the same advantages as the `image_tag()`.
  130. >**NOTE**
  131. >For radio buttons, the `id` attribute is not set by default to the value of the `name` attribute, but to a combination of the name and the value. That's because you need to have several radio button tags with the same name to obtain the automated "deselecting the previous one when selecting another" feature, and the `id=name` convention would imply having several HTML tags with the same `id` attribute in your page, which is strictly forbidden.
  132. -
  133. >**SIDEBAR**
  134. >Handling form submission
  135. >
  136. >How do you retrieve the data submitted by users through forms? It is available in the request parameters, so the action only needs to call `$request->getParameter($elementName)` to get the value.
  137. >
  138. >A good practice is to use the same action to display and handle the form. According to the request method (GET or POST), either the form template is called or the form is handled and the request is redirected to another action.
  139. >
  140. > [php]
  141. > // In mymodule/actions/actions.class.php
  142. > public function executeEditAuthor($request)
  143. > {
  144. > if (!$this->getRequest()->isMethod('post'))
  145. > {
  146. > // Display the form
  147. > return sfView::SUCCESS;
  148. > }
  149. > else
  150. > {
  151. > // Handle the form submission
  152. > $name = $request->getParameter('name');
  153. > ...
  154. > $this->redirect('mymodule/anotheraction');
  155. > }
  156. > }
  157. >
  158. >For this to work, the form target must be the same action as the one displaying it.
  159. >
  160. > [php]
  161. > // In mymodule/templates/editAuthorSuccess.php
  162. > <?php echo form_tag('mymodule/editAuthor') ?>
  163. >
  164. > ...
  165. Symfony offers specialized form helpers to do asynchronous requests in the background. The next chapter, which focuses on Ajax, provides more details.
  166. ### Date Input Widgets
  167. Forms are often used to retrieve dates. Dates in the wrong format are the main reason for form-submission failures. The `input_date_tag()` helper can assist the user in entering a date with an interactive JavaScript calendar, if you set the `rich` option to `true`, as shown in Figure 10-1.
  168. Figure 10-1 - Rich date input tag
  169. ![Rich date input tag](/images/book/F1001.png "Rich date input tag")
  170. If the `rich` option is omitted, the helper echoes three `<select>` tags populated with a range of months, days, and years. You can display these drop-downs separately by calling their helpers (`select_day_tag()`, `select_month_tag()`, and `select_year_tag()`). The default values of these elements are the current day, month, and year. Listing 10-3 shows the input date helpers.
  171. Listing 10-3 - Input Date Helpers
  172. [php]
  173. <?php echo input_date_tag('dateofbirth', '2005-05-03', 'rich=true') ?>
  174. => a text input tag together with a calendar widget
  175. // The following helpers require the DateForm helper group
  176. <?php use_helper('DateForm') ?>
  177. <?php echo select_day_tag('day', 1, 'include_custom=Choose a day') ?>
  178. => <select name="day" id="day">
  179. <option value="">Choose a day</option>
  180. <option value="1" selected="selected">01</option>
  181. <option value="2">02</option>
  182. ...
  183. <option value="31">31</option>
  184. </select>
  185. <?php echo select_month_tag('month', 1, 'include_custom=Choose a month use_short_month=true') ?>
  186. => <select name="month" id="month">
  187. <option value="">Choose a month</option>
  188. <option value="1" selected="selected">Jan</option>
  189. <option value="2">Feb</option>
  190. ...
  191. <option value="12">Dec</option>
  192. </select>
  193. <?php echo select_year_tag('year', 2007, 'include_custom=Choose a year year_end=2010') ?>
  194. => <select name="year" id="year">
  195. <option value="">Choose a year</option>
  196. <option value="2006">2006</option>
  197. <option value="2007" selected="selected">2007</option>
  198. ...
  199. </select>
  200. The accepted date values for the `input_date_tag()` helper are the ones recognized by the `strtotime()` PHP function. Listing 10-4 shows which formats can be used, and Listing 10-5 shows the ones that must be avoided.
  201. Listing 10-4 - Accepted Date Formats in Date Helpers
  202. [php]
  203. // Work fine
  204. <?php echo input_date_tag('test', '2006-04-01', 'rich=true') ?>
  205. <?php echo input_date_tag('test', 1143884373, 'rich=true') ?>
  206. <?php echo input_date_tag('test', 'now', 'rich=true') ?>
  207. <?php echo input_date_tag('test', '23 October 2005', 'rich=true') ?>
  208. <?php echo input_date_tag('test', 'next tuesday', 'rich=true') ?>
  209. <?php echo input_date_tag('test', '1 week 2 days 4 hours 2 seconds', 'rich=true') ?>
  210. // Return null
  211. <?php echo input_date_tag('test', null, 'rich=true') ?>
  212. <?php echo input_date_tag('test', '', 'rich=true') ?>
  213. Listing 10-5 - Incorrect Date Formats in Date Helpers
  214. [php]
  215. // Date zero = 01/01/1970
  216. <?php echo input_date_tag('test', 0, 'rich=true') ?>
  217. // Non-English date formats don't work
  218. <?php echo input_date_tag('test', '01/04/2006', 'rich=true') ?>
  219. ### Rich Text Editing
  220. Rich text editing is also possible in a `<textarea>` tag, thanks to the integration of the TinyMCE and FCKEditor widgets. They provide a word-processor-like interface with buttons to format text as bold, italic, and other styles, as shown in Figure 10-2.
  221. Figure 10-2 - Rich text editing
  222. ![Rich text editing](/images/book/F1002.png "Rich text editing")
  223. Both widgets require manual installation. As the procedure is the same for the two widgets, only the TinyMCE rich text editing is described here. You need to download the editor from the project website ([http://tinymce.moxiecode.com/](http://tinymce.moxiecode.com/)) and unpack it in a temporary folder. Copy the `tinymce/jscripts/tiny_mce/` directory into your project `web/js/` directory, and define the path to the library in `settings.yml`, as shown in Listing 10-6.
  224. Listing 10-6 - Setting Up the TinyMCE Library Path
  225. all:
  226. .settings:
  227. rich_text_js_dir: js/tiny_mce
  228. Once this is done, toggle the use of rich text editing in text areas by adding the `rich=true` option. You can also specify custom options for the JavaScript editor using the `tinymce_options` option. Listing 10-7 shows examples.
  229. Listing 10-7 - Rich Text Area
  230. [php]
  231. <?php echo textarea_tag('name', 'default content', 'rich=true size=10x20') ?>
  232. => a rich text edit zone powered by TinyMCE
  233. <?php echo textarea_tag('name', 'default content', 'rich=true size=10x20 tinymce_options=language:"fr",theme_advanced_buttons2:"separator"') ?>
  234. => a rich text edit zone powered by TinyMCE with custom parameters
  235. ### Country, Language and Currency Selection
  236. You may need to display a country selection field. But since country names are not the same in all languages, the options of a country drop-down list should vary according to the user culture (see Chapter 13 for more information about cultures). As shown in Listing 10-8, the `select_country_tag()` helper does it all for you: It internationalizes country names and uses the standard ISO country codes for values.
  237. Listing 10-8 - Select Country Tag Helper
  238. [php]
  239. <?php echo select_country_tag('country', 'AL') ?>
  240. => <select name="country" id="country">
  241. <option value="AF">Afghanistan</option>
  242. <option value="AL" selected="selected">Albania</option>
  243. <option value="DZ">Algeria</option>
  244. <option value="AS">American Samoa</option>
  245. ...
  246. Similar to `select_country_tag()` helper, the `select_language_tag()` helper displays a list of languages, as shown in Listing 10-9.
  247. Listing 10-9 - Select Language Tag Helper
  248. [php]
  249. <?php echo select_language_tag('language', 'en') ?>
  250. => <select name="language" id="language">
  251. ...
  252. <option value="elx">Elamite</option>
  253. <option value="en" selected="selected">English</option>
  254. <option value="enm">English, Middle (1100-1500)</option>
  255. <option value="ang">English, Old (ca.450-1100)</option>
  256. <option value="myv">Erzya</option>
  257. <option value="eo">Esperanto</option>
  258. ...
  259. The third helper is the `select_currency_tag()` helper, that displays a list of currencies, as shown in Listing 10-10.
  260. Listing 10-10 - Select Currency Tag Helper
  261. [php]
  262. <?php echo select_currency_tag('currency', 'EUR') ?>
  263. => <select name="currency" id="currency">
  264. ...
  265. <option value="ETB">Ethiopian Birr</option>
  266. <option value="ETD">Ethiopian Dollar</option>
  267. <option value="EUR" selected="selected">Euro</option>
  268. <option value="XBA">European Composite Unit</option>
  269. <option value="XEU">European Currency Unit</option>
  270. ...
  271. >**NOTE**
  272. >All three helpers accept a third parameter which is an options array. It can restrict the displayed options to a certain set: `array('countries' => array ('FR', 'DE'))`. For `select_language_tag()` the option is named `languages` and for `select_currency_tag()` it is named `currencies`.
  273. >In most cases it makes sense to restrict the set to a list of known and supported values, especially as the lists could contain outdated items.
  274. >
  275. >`select_currency_tag()` offers an additional option named `display` that influences what is displayed in the option. This can be set to one of `symbol`,`code` or `name`
  276. Form Helpers for Objects
  277. ------------------------
  278. When form elements are used to edit the properties of an object, standard link helpers can become tedious to write. For instance, to edit the `telephone` attribute of a `Customer` object, you would write this:
  279. [php]
  280. <?php echo input_tag('telephone', $customer->getTelephone()) ?>
  281. => <input type="text" name="telephone" id="telephone" value="0123456789" />
  282. To avoid repeating the attribute name, symfony provides an alternative object form helper for each form helper. An object form helper deduces the name and the default value of a form element from an object and a method name. The previous `input_tag()` is equivalent to this:
  283. [php]
  284. <?php echo object_input_tag($customer, 'getTelephone') ?>
  285. => <input type="text" name="telephone" id="telephone" value="0123456789" />
  286. The economy might not look crucial for the `object_input_tag()`. However, every standard form helper has a corresponding object form helper, and they all share the same syntax. It makes generation of forms quite straightforward. That's why the object form helpers are used extensively in the scaffolding and generated administrations (see Chapter 14). Listing 10-11 lists the object form helpers.
  287. Listing 10-11 - Object Form Helpers Syntax
  288. [php]
  289. <?php echo object_input_tag($object, $method, $options) ?>
  290. <?php echo object_input_date_tag($object, $method, $options) ?>
  291. <?php echo object_input_hidden_tag($object, $method, $options) ?>
  292. <?php echo object_textarea_tag($object, $method, $options) ?>
  293. <?php echo object_checkbox_tag($object, $method, $options) ?>
  294. <?php echo object_select_tag($object, $method, $options) ?>
  295. <?php echo object_select_country_tag($object, $method, $options) ?>
  296. <?php echo object_select_language_tag($object, $method, $options) ?>
  297. There is no `object_password_tag()` helper, since it is a bad practice to give a default value to a password tag, based on something the user has previously entered.
  298. >**CAUTION**
  299. >Unlike the regular form helpers, the object form helpers are available only if you declare explicitly the use of the `Object` helper group in your template with `use_helper('Object')`.
  300. The most interesting of all object form helpers are `objects_for_select()` and `object_select_tag()`, which concern drop-down lists.
  301. ### Populating Drop-Down Lists with Objects
  302. The `options_for_select()` helper, described previously with the other standard helpers, transforms a PHP associative array into an options list, as shown in Listing 10-12.
  303. Listing 10-12 - Creating a List of Options Based on an Array with `options_for_select()`
  304. [php]
  305. <?php echo options_for_select(array(
  306. '1' => 'Steve',
  307. '2' => 'Bob',
  308. '3' => 'Albert',
  309. '4' => 'Ian',
  310. '5' => 'Buck'
  311. ), 4) ?>
  312. => <option value="1">Steve</option>
  313. <option value="2">Bob</option>
  314. <option value="3">Albert</option>
  315. <option value="4" selected="selected">Ian</option>
  316. <option value="5">Buck</option>
  317. Suppose that you already have an array of objects of class `Author`, resulting from a Propel query. If you want to build a list of options based on this array, you will need to loop on it to retrieve the `id` and the `name` of each object, as shown in Listing 10-13.
  318. Listing 10-13 - Creating a List of Options Based on an Array of Objects with `options_for_select()`
  319. [php]
  320. // In the action
  321. $options = array();
  322. foreach ($authors as $author)
  323. {
  324. $options[$author->getId()] = $author->getName();
  325. }
  326. $this->options = $options;
  327. // In the template
  328. <?php echo options_for_select($options, 4) ?>
  329. This kind of processing happens so often that symfony has a helper to automate it: `objects_for_select()`, which creates an option list based directly on an array of objects. The helper needs two additional parameters: the method names used to retrieve the `value` and the text contents of the `<option>` tags to be generated. So Listing 10-13 is equivalent to this simpler form:
  330. [php]
  331. <?php echo objects_for_select($authors, 'getId', 'getName', 4) ?>
  332. That's smart and fast, but symfony goes even further, when you deal with foreign key columns.
  333. ### Creating a Drop-Down List Based on a Foreign Key Column
  334. The values a foreign key column can take are the primary key values of the foreign table records. If, for instance, the `article` table has an `author_id` column that is a foreign key to an `author` table, the possible values for this column are the `id` of all the records of the `author` table. Basically, a drop-down list to edit the author of an article would look like Listing 10-14.
  335. Listing 10-14 - Creating a List of Options Based on a Foreign Key with `objects_for_select()`
  336. [php]
  337. <?php echo select_tag('author_id', objects_for_select(
  338. AuthorPeer::doSelect(new Criteria()),
  339. 'getId',
  340. '__toString',
  341. $article->getAuthorId()
  342. )) ?>
  343. => <select name="author_id" id="author_id">
  344. <option value="1">Steve</option>
  345. <option value="2">Bob</option>
  346. <option value="3">Albert</option>
  347. <option value="4" selected="selected">Ian</option>
  348. <option value="5">Buck</option>
  349. </select>
  350. The `object_select_tag()` does all that by itself. It displays a drop-down list populated with the name of the possible records of the foreign table. The helper can guess the foreign table and foreign column from the schema, so its syntax is very concise. Listing 10-13 is equivalent to this:
  351. [php]
  352. <?php echo object_select_tag($article, 'getAuthorId') ?>
  353. The `object_select_tag()` helper guesses the related peer class name (`AuthorPeer` in the example) based on the method name passed as a parameter. However, you can specify your own class by setting the `related_class` option in the third argument. The text content of the `<option>` tags is the record name, which is the result of the `__toString()` method of the object class (if `$author->__toString()` method is undefined, the primary key is used instead). In addition, the list of options is built from a doSelect() method with an empty criteria value; it returns all the records ordered by creation date. If you prefer to display only a subset of records with a specific ordering, create a method in the peer class returning this selection as an array of objects, and set it in the `peer_method` option. Lastly, you can add a blank option or a custom option at the top of the drop-down list by setting the include_blank and include_custom options. Listing 10-15 demonstrates these different options for the `object_select_tag()` helper.
  354. Listing 10-15 - Options of the `object_select_tag()` Helper
  355. [php]
  356. // Base syntax
  357. <?php echo object_select_tag($article, 'getAuthorId') ?>
  358. // Builds the list from AuthorPeer::doSelect(new Criteria())
  359. // Change the peer class used to retrieve the possible values
  360. <?php echo object_select_tag($article, 'getAuthorId', 'related_class=Foobar') ?>
  361. // Builds the list from FoobarPeer::doSelect(new Criteria())
  362. // Change the peer method used to retrieve the possible values
  363. <?php echo object_select_tag($article, 'getAuthorId','peer_method=getMostFamousAuthors') ?>
  364. // Builds the list from AuthorPeer::getMostFamousAuthors(new Criteria())
  365. // Add an <option value="">&nbsp;</option> at the top of the list
  366. <?php echo object_select_tag($article, 'getAuthorId', 'include_blank=true') ?>
  367. // Add an <option value="">Choose an author</option> at the top of the list
  368. <?php echo object_select_tag($article, 'getAuthorId',
  369. 'include_custom=Choose an author') ?>
  370. ### Updating Objects
  371. A form completely dedicated to editing object properties by using object helpers is easier to handle in an action. For instance, if you have an object of class `Author` with `name`, `age`, and `address` attributes, the form can be coded as shown in Listing 10-16.
  372. Listing 10-16 - A Form with Only Object Helpers
  373. [php]
  374. <?php echo form_tag('author/update') ?>
  375. <?php echo object_input_hidden_tag($author, 'getId') ?>
  376. Name: <?php echo object_input_tag($author, 'getName') ?><br />
  377. Age: <?php echo object_input_tag($author, 'getAge') ?><br />
  378. Address: <br />
  379. <?php echo object_textarea_tag($author, 'getAddress') ?>
  380. </form>
  381. The `update` action of the `author` module, called when the form is submitted, can simply update the object with the `fromArray()` modifier generated by Propel, as shown in Listing 10-17.
  382. Listing 10-17 - Handling a Form Submission Based on Object Form Helpers
  383. [php]
  384. public function executeUpdate($request)
  385. {
  386. $author = AuthorPeer::retrieveByPk($request->getParameter('id'));
  387. $this->forward404Unless($author);
  388. $author->fromArray($this->getRequest()->getParameterHolder()->getAll(),BasePeer::TYPE_FIELDNAME);
  389. $author->save();
  390. return $this->redirect('/author/show?id='.$author->getId());
  391. }
  392. Form Validation
  393. ---------------
  394. >**NOTE**
  395. >The features described in this section are deprecated in symfony 1.1 and only work if you enable the `sfCompat10` plugin.
  396. Chapter 6 explained how to use the `validateXXX()` methods in the action class to validate the request parameters. However, if you use this technique to validate a form submission, you will end up rewriting the same portion of code over and over. Symfony provides an alternative form-validation technique, relying on only a YAML file, instead of PHP code in the action class.
  397. To demonstrate the form-validation features, let's first consider the sample form shown in Listing 10-18. It is a classic contact form, with `name`, `email`, `age`, and `message` fields.
  398. Listing 10-18 - Sample Contact Form, in `modules/contact/templates/indexSuccess.php`
  399. [php]
  400. <?php echo form_tag('contact/send') ?>
  401. Name: <?php echo input_tag('name') ?><br />
  402. Email: <?php echo input_tag('email') ?><br />
  403. Age: <?php echo input_tag('age') ?><br />
  404. Message: <?php echo textarea_tag('message') ?><br />
  405. <?php echo submit_tag() ?>
  406. </form>
  407. The principle of form validation is that if a user enters invalid data and submits the form, the next page should show an error message. Let's define what valid data should be for the sample form, in plain English:
  408. * The `name` field is required. It must be a text entry between 2 and 100 characters.
  409. * The `email` field is required. It must be a text entry between 2 and 100 characters, and it must be a valid e-mail address.
  410. * The `age` field is required. It must be an integer between 0 and 120.
  411. * The `message` field is required.
  412. You could define more complex validation rules for the contact form, but these are just fine for a demonstration of the validation possibilities.
  413. >**NOTE**
  414. >Form validation can occur on the server side and/or on the client side. The server-side validation is compulsory to avoid corrupting a database with wrong data. The client-side validation is optional, though it greatly enhances the user experience. The client-side validation is to be done with custom JavaScript.
  415. ### Validators
  416. You can see that the `name` and `email` fields in the example share common validation rules. Some validation rules appear so often in web forms that symfony packages the PHP code that implements them into validators. A validator is simple class that provides an `execute()` method. This method expects the value of a field as parameter, and returns `true` if the value is valid and `false` otherwise.
  417. Symfony ships with several validators (described in the "Standard Symfony Validators" section later in this chapter), but let's focus on the `sfStringValidator` for now. This validator checks that an input is a string, and that its size is between two specified character amounts (defined when calling the `initialize()` method). That's exactly what is required to validate the `name` field. Listing 10-19 shows how to use this validator in a validation method.
  418. Listing 10-19 - Validating Request Parameters with Reusable Validators, in `modules/contact/action/actions.class.php`
  419. [php]
  420. public function validateSend($request)
  421. {
  422. $name = $request->getParameter('name');
  423. // The name field is required
  424. if (!$name)
  425. {
  426. $this->getRequest()->setError('name', 'The name field cannot be left blank');
  427. return false;
  428. }
  429. // The name field must be a text entry between 2 and 100 characters
  430. $myValidator = new sfStringValidator($this->getContext(), array(
  431. 'min' => 2,
  432. 'min_error' => 'This name is too short (2 characters minimum)',
  433. 'max' => 100,
  434. 'max_error' => 'This name is too long. (100 characters maximum)',
  435. ));
  436. if (!$myValidator->execute($name, $error))
  437. {
  438. return false;
  439. }
  440. return true;
  441. }
  442. If a user submits the form in Listing 10-18 with the value `a` in the `name` field, the `execute()` method of the `sfStringValidator` will return `false` (because the string length is less than the minimum of two characters). The `validateSend()` method will then fail, and the `handleErrorSend()` method will be called instead of the `executeSend()` method.
  443. >**TIP**
  444. >The `setError()` method of the `sfRequest` method gives information to the template so that it can display an error message (as explained in the "Displaying the Error Messages in the Form" section later in this chapter). The validators set the errors internally, so you can define different errors for the different cases of nonvalidation. That's the purpose of the `min_error` and `max_error` initialization parameters of the `sfStringValidator`.
  445. All the rules defined in the example can be translated into validators:
  446. * `name`: `sfStringValidator` (`min=2`, `max=100`)
  447. * `email`: `sfStringValidator` (`min=2`, `max=100`) and `sfEmailValidator`
  448. * `age`: `sfNumberValidator` (`min=0`, `max=120`)
  449. The fact that a field is required is not handled by a validator.
  450. ### Validation File
  451. You could easily implement the validation of the contact form with validators in the `validateSend()` method PHP, but that would imply repeating a lot of code. Symfony offers an alternative way to define validation rules for a form, and it involves YAML. For instance, Listing 10-20 shows the translation of the name field validation rules, and its results are equivalent to those of Listing 10-19.
  452. Listing 10-20 - Validation File, in `modules/contact/validate/send.yml`
  453. fields:
  454. name:
  455. required:
  456. msg: The name field cannot be left blank
  457. sfStringValidator:
  458. min: 2
  459. min_error: This name is too short (2 characters minimum)
  460. max: 100
  461. max_error: This name is too long. (100 characters maximum)
  462. In a validation file, the `fields` header lists the fields that need to be validated, if they are required, and the validators that should be tested on them when a value is present. The parameters of each validator are the same as those you would use to initialize the validator manually. A field can be validated by as many validators as necessary.
  463. >**NOTE**
  464. >The validation process doesn't stop when a validator fails. Symfony tests all the validators and declares the validation failed if at least one of them fails. And even if some of the rules of the validation file fail, symfony will still look for a `validateXXX()` method and execute it. So the two validation techniques are complementary. The advantage is that, in a form with multiple failures, all the error messages are shown.
  465. Validation files are located in the module `validate/` directory, and named by the action they must validate. For example, Listing 10-19 must be stored in a file called `validate/send.yml`.
  466. ### Redisplaying the Form
  467. By default, symfony looks for a `handleErrorSend()` method in the action class whenever the validation process fails, or displays the `sendError.php` template if the method doesn't exist.
  468. The usual way to inform the user of a failed validation is to display the form again with an error message. To that purpose, you need to override the `handleErrorSend()` method and end it with a redirection to the action that displays the form (in the example, `module/index`), as shown in Listing 10-21.
  469. Listing 10-21 - Displaying the Form Again, in `modules/contact/actions/actions.class.php`
  470. [php]
  471. class ContactActions extends sfActions
  472. {
  473. public function executeIndex()
  474. {
  475. // Display the form
  476. }
  477. public function handleErrorSend()
  478. {
  479. $this->forward('contact', 'index');
  480. }
  481. public function executeSend()
  482. {
  483. // Handle the form submission
  484. }
  485. }
  486. If you choose to use the same action to display the form and handle the form submission, then the `handleErrorSend()` method can simply return `sfView::SUCCESS` to redisplay the form from `sendSuccess.php`, as shown in Listing 10-22.
  487. Listing 10-22 - A Single Action to Display and Handle the Form, in `modules/contact/actions/actions.class.php`
  488. [php]
  489. class ContactActions extends sfActions
  490. {
  491. public function executeSend()
  492. {
  493. if (!$this->getRequest()->isMethod('post'))
  494. {
  495. // Prepare data for the template
  496. // Display the form
  497. return sfView::SUCCESS;
  498. }
  499. else
  500. {
  501. // Handle the form submission
  502. ...
  503. $this->redirect('mymodule/anotheraction');
  504. }
  505. }
  506. public function handleErrorSend()
  507. {
  508. // Prepare data for the template
  509. // Display the form
  510. return sfView::SUCCESS;
  511. }
  512. }
  513. The logic necessary to prepare the data can be refactored into a protected method of the action class, to avoid repeating it in the `executeSend()` and `handleErrorSend()` methods.
  514. With this new configuration, when the user types an invalid name, the form is displayed again, but the entered data is lost and no error message explains the reason of the failure. To address the last issue, you must modify the template that displays the form, to insert error messages close to the faulty field.
  515. ### Displaying the Error Messages in the Form
  516. The error messages defined as validator parameters are added to the request when a field fails validation (just as you can add an error manually with the `setError()` method, as in Listing 10-19). The `sfRequest` object provides two useful methods to retrieve the error message: `hasError()` and `getError()`, which each expect a field name as parameter. In addition, you can display an alert at the top of the form to draw attention to the fact that one or many of the fields contain invalid data with the `hasErrors()` method. Listings 10-23 and 10-24 demonstrate how to use these methods.
  517. Listing 10-23 - Displaying Error Messages at the Top of the Form, in `templates/indexSuccess.php`
  518. [php]
  519. <?php if ($sf_request->hasErrors()): ?>
  520. <p>The data you entered seems to be incorrect.
  521. Please correct the following errors and resubmit:</p>
  522. <ul>
  523. <?php foreach($sf_request->getErrors() as $name => $error): ?>
  524. <li><?php echo $name ?>: <?php echo $error ?></li>
  525. <?php endforeach; ?>
  526. </ul>
  527. <?php endif; ?>
  528. Listing 10-24 - Displaying Error Messages Inside the Form, in `templates/indexSuccess.php`
  529. [php]
  530. <?php echo form_tag('contact/send') ?>
  531. <?php if ($sf_request->hasError('name')): ?>
  532. <?php echo $sf_request->getError('name') ?> <br />
  533. <?php endif; ?>
  534. Name: <?php echo input_tag('name') ?><br />
  535. ...
  536. <?php echo submit_tag() ?>
  537. </form>
  538. The conditional use of the `getError()` method in Listing 10-23 is a bit long to write. That's why symfony offers a `form_error()` helper to replace it, provided that you declare the use of its helper group, `Validation`. Listing 10-25 replaces Listing 10-24 by using this helper.
  539. Listing 10-25 - Displaying Error Messages Inside the Form, the Short Way
  540. [php]
  541. <?php use_helper('Validation') ?>
  542. <?php echo form_tag('contact/send') ?>
  543. <?php echo form_error('name') ?><br />
  544. Name: <?php echo input_tag('name') ?><br />
  545. ...
  546. <?php echo submit_tag() ?>
  547. </form>
  548. The `form_error()` helper adds a special character before and after each error message to make the messages more visible. By default, the character is an arrow pointing down (corresponding to the `&darr;` entity), but you can change it in the `settings.yml` file:
  549. all:
  550. .settings:
  551. validation_error_prefix: ' &darr;&nbsp;'
  552. validation_error_suffix: ' &nbsp;&darr;'
  553. In case of failed validation, the form now displays errors correctly, but the data entered by the user is lost. You need to repopulate the form to make it really user-friendly.
  554. ### Repopulating the Form
  555. As the error handling is done through the `forward()` method (shown in Listing 10-21), the original request is still accessible, and the data entered by the user is in the request parameters. So you could repopulate the form by adding default values to each field, as shown in Listing 10-26.
  556. Listing 10-26 - Setting Default Values to Repopulate the Form When Validation Fails, in `templates/indexSuccess.php`
  557. [php]
  558. <?php use_helper('Validation') ?>
  559. <?php echo form_tag('contact/send') ?>
  560. <?php echo form_error('name') ?><br />
  561. Name: <?php echo input_tag('name', $sf_params->get('name')) ?><br />
  562. <?php echo form_error('email') ?><br />
  563. Email: <?php echo input_tag('email', $sf_params->get('email')) ?><br />
  564. <?php echo form_error('age') ?><br />
  565. Age: <?php echo input_tag('age', $sf_params->get('age')) ?><br />
  566. <?php echo form_error('message') ?><br />
  567. Message: <?php echo textarea_tag('message', $sf_params->get('message')) ?><br />
  568. <?php echo submit_tag() ?>
  569. </form>
  570. But once again, this is quite tedious to write. Symfony provides an alternative way of triggering repopulation for all the fields of a form, directly in the YAML validation file, without changing the default values of the elements. Just enable the `fillin:` feature for the form, with the syntax described in Listing 10-27.
  571. Listing 10-27 - Activating `fillin` to Repopulate the Form When Validation Fails, in `validate/send.yml`
  572. fillin:
  573. enabled: true # Enable the form repopulation
  574. param:
  575. name: test # Form name, not needed if there is only one form in the page
  576. skip_fields: [email] # Do not repopulate these fields
  577. exclude_types: [hidden, password] # Do not repopulate these field types
  578. check_types: [text, checkbox, radio, select, hidden] # Do repopulate these
  579. content_type: html # html is the tolerant default. Other option is xml and xhtml (same as xml but without xml prolog)
  580. By default, the automatic repopulation works for text inputs, check boxes, radio buttons, text areas, and select components (simple and multiple), but it does not repopulate password or hidden tags. The `fillin` feature doesn't work for file tags.
  581. >**NOTE**
  582. >The `fillin` feature works by parsing the response content in XML just before sending it to the user. By default `fillin` will output HTML.
  583. >
  584. >If you want to have `fillin` to output XHTML you have to set `param: content_type: xml`. If the response is not a strictly valid XHTML document `fillin` will not work.
  585. >The third available `content_type` is `xhtml` which is the same as `xml` but it removes the xml prolog from the response which causes quirks mode in IE6.
  586. You might want to transform the values entered by the user before writing them back in a form input. Escaping, URL rewriting, transformation of special characters into entities, and all the other transformations that can be called through a function can be applied to the fields of your form if you define the transformation under the `converters:` key, as shown in Listing 10-28.
  587. Listing 10-28 - Converting Input Before `fillin`, in `validate/send.yml`
  588. fillin:
  589. enabled: true
  590. param:
  591. name: test
  592. converters: # Converters to apply
  593. htmlentities: [first_name, comments]
  594. htmlspecialchars: [comments]
  595. ### Standard Symfony Validators
  596. Symfony contains some standard validators that can be used for your forms:
  597. * `sfStringValidator`
  598. * `sfNumberValidator`
  599. * `sfEmailValidator`
  600. * `sfUrlValidator`
  601. * `sfRegexValidator`
  602. * `sfCompareValidator`
  603. * `sfPropelUniqueValidator`
  604. * `sfDoctrineUniqueValidator`
  605. * `sfFileValidator`
  606. * `sfCallbackValidator`
  607. * `sfDateValidator`
  608. Each has a default set of parameters and error messages, but you can easily
  609. override them through the `initialize()` validator method or in the YAML file.
  610. The following sections describe the validators and show usage examples.
  611. #### String Validator
  612. `sfStringValidator` allows you to apply string-related constraints to a parameter.
  613. sfStringValidator:
  614. values: [foo, bar]
  615. values_error: The only accepted values are foo and bar
  616. insensitive: false # If true, comparison with values is case insensitive
  617. min: 2
  618. min_error: Please enter at least 2 characters
  619. max: 100
  620. max_error: Please enter less than 100 characters
  621. #### Number Validator
  622. `sfNumberValidator` verifies if a parameter is a number and allows you to apply size constraints.
  623. sfNumberValidator:
  624. nan_error: Please enter an integer
  625. min: 0
  626. min_error: The value must be at least zero
  627. max: 100
  628. max_error: The value must be less than or equal to 100
  629. #### E-Mail Validator
  630. `sfEmailValidator` verifies if a parameter contains a value that qualifies as an e-mail address.
  631. sfEmailValidator:
  632. strict: true
  633. email_error: This email address is invalid
  634. RFC822 defines the format of e-mail addresses. However, it is more permissive than the generally accepted format. For instance, `me@localhost` is a valid e-mail address according to the RFC, but you probably don't want to accept it. When the `strict` parameter is set to `true` (its default value), only e-mail addresses matching the pattern `name@domain.extension` are valid. When set to `false`, RFC822 is used as a rule.
  635. #### URL Validator
  636. `sfUrlValidator` checks if a field is a correct URL.
  637. sfUrlValidator:
  638. url_error: This URL is invalid
  639. #### Regular Expression Validator
  640. `sfRegexValidator` allows you to match a value against a Perl-compatible regular expression pattern.
  641. sfRegexValidator:
  642. match: No
  643. match_error: Posts containing more than one URL are considered as spam
  644. pattern: /http.*http/si
  645. The `match` parameter determines if the request parameter must match the pattern to be valid (value `Yes`) or match the pattern to be invalid (value `No`).
  646. #### Compare Validator
  647. `sfCompareValidator` compares two different request parameters. It is very useful for password checks.
  648. fields:
  649. password1:
  650. required:
  651. msg: Please enter a password
  652. password2:
  653. required:
  654. msg: Please retype the password
  655. sfCompareValidator:
  656. check: password1
  657. compare_error: The two passwords do not match
  658. The `check` parameter contains the name of the field that the current field must match to be valid.
  659. By default, the validator checks the equality of the parameters. You can change this behavior be specifying an `operator` parameter. Available operators are: `>`, `>=`, `<`, `<=`, `==` and `!=`.
  660. #### Propel/Doctrine Unique Validators
  661. `sfPropelUniqueValidator` validates that the value of a request parameter
  662. doesn't already exist in your database. It is very useful for unique indexes.
  663. fields:
  664. nickname:
  665. sfPropelUniqueValidator:
  666. class: User
  667. column: login
  668. unique_error: This login already exists. Please choose another one.
  669. In this example, the validator will look in the database for a record of class
  670. `User` where the `login` column has the same value as the field to validate.
  671. >**CAUTION**
  672. >sfPropelUniqueValidator is susceptible to race conditions. Although unlikely,
  673. in multiuser environments, the result may change the instant it returns. You
  674. should still be ready to handle a duplicate INSERT error.
  675. >**NOTE**
  676. >If you have enabled the Doctrine ORM for your project, you can also use the
  677. >`sfDoctrineUniqueValidator` in the same way as described above for Propel.
  678. #### File Validator
  679. `sfFileValidator` applies format (an array of mime-types) and size constraints to file upload fields.
  680. fields:
  681. image:
  682. file: True
  683. required:
  684. msg: Please upload an image file
  685. sfFileValidator:
  686. mime_types:
  687. - 'image/jpeg'
  688. - 'image/png'
  689. - 'image/x-png'
  690. - 'image/pjpeg'
  691. mime_types_error: Only PNG and JPEG images are allowed
  692. max_size: 512000
  693. max_size_error: Max size is 512Kb
  694. Be aware that the `file` attribute must be set to `True` for the field, and the template must declare the form as multipart.
  695. #### Callback Validator
  696. `sfCallbackValidator` delegates the validation to a third-party callable method or function to do the validation. The callable method or function must return `true` or `false`.
  697. fields:
  698. account_number:
  699. sfCallbackValidator:
  700. callback: is_numeric
  701. invalid_error: Please enter a number.
  702. credit_card_number:
  703. sfCallbackValidator:
  704. callback: [myTools, validateCreditCard]
  705. invalid_error: Please enter a valid credit card number.
  706. The callback method or function receives the value to be validated as a first parameter. This is very useful when you want to reuse existing methods of functions, rather than create a full validator class.
  707. #### Date Validator
  708. `sfDateValidator` checks that a submitted date is valid and/or within a certain
  709. simple range
  710. sfDateValidator:
  711. date_error: You have entered an invalid date
  712. compare: "2007-05-01"
  713. operator: ">=" #defaults to "==" if not supplied
  714. compare_error: "Enter a date later than 1st May 2007"
  715. >**TIP**
  716. >You can also write your own validators, as described in the "Creating a Custom Validator" section later in this chapter.
  717. ### Named Validators
  718. If you see that you need to repeat a validator class and its settings, you can package it under a named validator. In the example of the contact form, the email field needs the same sfStringValidator parameters as the `name` field. So you can create a `myStringValidator` named validator to avoid repeating the same settings twice. To do so, add a `myStringValidator` label under the `validators:` header, and set the `class` and `param` keys with the details of the named validator you want to package. You can then use the named validator just like a regular one in the `fields` section, as shown in Listing 10-29.
  719. Listing 10-29 - Reusing Named Validators in a Validation File, in `validate/send.yml`
  720. validators:
  721. myStringValidator:
  722. class: sfStringValidator
  723. param:
  724. min: 2
  725. min_error: This field is too short (2 characters minimum)
  726. max: 100
  727. max_error: This field is too long (100 characters maximum)
  728. fields:
  729. name:
  730. required:
  731. msg: The name field cannot be left blank
  732. myStringValidator:
  733. email:
  734. required:
  735. msg: The email field cannot be left blank
  736. myStringValidator:
  737. sfEmailValidator:
  738. email_error: This email address is invalid
  739. ### Restricting the Validation to a Method
  740. By default, the validators set in a validation file are run when the action is called with the POST method. You can override this setting globally or field by field by specifying another value in the `methods` key, to allow a different validation for different methods, as shown in Listing 10-30.
  741. Listing 10-30 - Defining When to Test a Field, in `validate/send.yml`
  742. methods: [post] # This is the default setting
  743. fields:
  744. name:
  745. required:
  746. msg: The name field cannot be left blank
  747. myStringValidator:
  748. email:
  749. methods: [post, get] # Overrides the global methods settings
  750. required:
  751. msg: The email field cannot be left blank
  752. myStringValidator:
  753. sfEmailValidator:
  754. email_error: This email address is invalid
  755. ### What Does a Validation File Look Like?
  756. So far, you have seen only bits and pieces of a validation file. When you put everything together, the validation rules find a clear translation in YAML. Listing 10-31 shows the complete validation file for the sample contact form, corresponding to all the rules defined earlier in the chapter.
  757. Listing 10-31 - Sample Complete Validation File
  758. fillin:
  759. enabled: true
  760. validators:
  761. myStringValidator:
  762. class: sfStringValidator
  763. param:
  764. min: 2
  765. min_error: This field is too short (2 characters minimum)
  766. max: 100
  767. max_error: This field is too long (100 characters maximum)
  768. fields:
  769. name:
  770. required:
  771. msg: The name field cannot be left blank
  772. myStringValidator:
  773. email:
  774. required:
  775. msg: The email field cannot be left blank
  776. myStringValidator:
  777. sfEmailValidator:
  778. email_error: This email address is invalid
  779. age:
  780. sfNumberValidator:
  781. nan_error: Please enter an integer
  782. min: 0
  783. min_error: "You're not even born. How do you want to send a message?"
  784. max: 120
  785. max_error: "Hey, grandma, aren't you too old to surf on the Internet?"
  786. message:
  787. required:
  788. msg: The message field cannot be left blank
  789. Complex Validation
  790. ------------------
  791. The validation file satisfies most needs, but when the validation is very complex, it might not be sufficient. In this case, you can still return to the `validateXXX()` method in the action, or find the solution to your problem in the following sections.
  792. ### Creating a Custom Validator
  793. Each validator is a class that extends the `sfValidator` class. If the validator classes shipped with symfony are not suitable for your needs, you can easily create a new one, in any of the `lib/` directories where it can be autoloaded. The syntax is quite simple: The `execute()` method of the validator is called when the validator is executed. You can also define default settings in the `initialize()` method.
  794. The `execute()` method receives the value to validate as the first parameter and the error message to throw as the second parameter. Both are passed as references, so you can modify the error message from within the method.
  795. The `initialize()` method receives the context singleton and the array of parameters from the YAML file. It must first call the `initialize()` method of its parent `sfValidator` class, and then set the default values.
  796. Every validator has a parameter holder accessible by `$this->getParameterHolder()`.
  797. For instance, if you want to build an `sfSpamValidator` to check if a string is not spam, add the code shown in Listing 10-32 to an `sfSpamValidator.class.php` file. It checks if the `$value` contains more than `max_url` times the string `'http'`.
  798. Listing 10-32 - Creating a Custom Validator, in `lib/sfSpamValidator.class.php`
  799. [php]
  800. class sfSpamValidator extends sfValidator
  801. {
  802. public function execute(&$value, &$error)
  803. {
  804. // For max_url=2, the regexp is /http.*http/is
  805. $re = '/'.implode('.*', array_fill(0, $this->getParameter('max_url') + 1, 'http')).'/is';
  806. if (preg_match($re, $value))
  807. {
  808. $error = $this->getParameter('spam_error');
  809. return false;
  810. }
  811. return true;
  812. }
  813. public function initialize ($context, $parameters = null)
  814. {
  815. // Initialize parent
  816. parent::initialize($context);
  817. // Set default parameters value
  818. $this->setParameter('max_url', 2);
  819. $this->setParameter('spam_error', 'This is spam');
  820. // Set parameters
  821. $this->getParameterHolder()->add($parameters);
  822. return true;
  823. }
  824. }
  825. As soon as the validator is added to an autoloadable directory (and the cache cleared), you can use it in your validation files, as shown in Listing 10-33.
  826. Listing 10-33 - Using a Custom Validator, in `validate/send.yml`
  827. fields:
  828. message:
  829. required:
  830. msg: The message field cannot be left blank
  831. sfSpamValidator:
  832. max_url: 3
  833. spam_error: Leave this site immediately, you filthy spammer!
  834. ### Using Array Syntax for Form Fields
  835. PHP allows you to use an array syntax for the form fields. When writing your own forms, or when using the ones generated by the Propel administration (see Chapter 14), you may end up with HTML code that looks like Listing 10-34.
  836. Listing 10-34 - Form with Array Syntax
  837. [php]
  838. <label for="story_title">Title:</label>
  839. <input type="text" name="story[title]" id="story_title" value="default value"
  840. size="45" />
  841. Using the input name as is (with brackets) in a validation file will throw a parsed-induced error. The solution here is to replace square brackets `[]` with curly brackets `{}` in the `fields` section, as shown in Listing 10-35, and symfony will take care of the conversion of the names sent to the validators afterwards.
  842. Listing 10-35 - Validation File for a Form with Array Syntax
  843. fields:
  844. story{title}:
  845. required: Yes
  846. ### Executing a Validator on an Empty Field
  847. You may need to execute a validator on a field that is not required, on an empty value. For instance, this happens with a form where the user can change their password (but may not want to), and in this case, a confirmation password must be entered. See the example in Listing 10-36.
  848. Listing 10-36 - Sample Validation File for a Form with Two Password Fields
  849. fields:
  850. password1:
  851. password2:
  852. sfCompareValidator:
  853. check: password1
  854. compare_error: The two passwords do not match
  855. The validation process executes as follows:
  856. * If `password1` `== null` and `password2 == null`:
  857. * The `required` test passes.
  858. * Validators are not run.
  859. * The form is valid.
  860. * If `password2 == null` while `password1` is not `null`:
  861. * The `required` test passes.
  862. * Validators are not run.
  863. * The form is valid.
  864. You may want to execute your `password2` validator if `password1` is `not null`. Fortunately, the symfony validators handle this case, thanks to the `group` parameter. When a field is in a group, its validator will execute if it is not empty and if one of the fields of the same group is not empty.
  865. So, if you change the configuration to that shown in Listing 10-37, the validation process behaves correctly.
  866. Listing 10-37 - Sample Validation File for a Form with Two Password Fields and a Group
  867. fields:
  868. password1:
  869. group: password_group
  870. password2:
  871. group: password_group
  872. sfCompareValidator:
  873. check: password1
  874. compare_error: The two passwords do not match
  875. The validation process now executes as follows:
  876. * If `password1 == null` and `password2 == null`:
  877. * The `required` test passes.
  878. * Validators are not run.
  879. * The form is valid.
  880. * If `password1 == null` and `password2 == 'foo'`:
  881. * The `required` test passes.
  882. * `password2` is `not null`, so its validator is executed, and it fails.
  883. * An error message is thrown for `password2`.
  884. * If `password1 == 'foo'` and `password2 == null`:
  885. * The `required` test passes.
  886. * `password1` is `not null`, so the validator for `password2`, which is in the same group, is executed, and it fails.
  887. * An error message is thrown for `password2`.
  888. * If `password1 == 'foo'` and `password2 == 'foo'`:
  889. * The `required` test passes.
  890. * `password2` is `not null`, so its validator is executed, and it passes.
  891. * The form is valid.
  892. Summary
  893. -------
  894. Writing forms in symfony templates is facilitated by the standard form helpers and their smart options. When you design a form to edit the properties of an object, the object form helpers simplify the task a great deal. The validation files, validation helpers, and repopulation feature reduce the work necessary to build a robust and user-friendly server control on the value of a field. And even the most complex validation needs can be handled, either by writing a custom validator or by creating a `validateXXX()` method in the action class.