1 <?xml version="1.0" encoding="UTF-8"?>
3 <sect1 id="zend.view.helpers" xmlns:xi="http://www.w3.org/2001/XInclude">
4 <title>View Helpers</title>
7 In your view scripts, often it is necessary to perform certain
8 complex functions over and over: e.g., formatting a date,
9 generating form elements, or displaying action links. You can
10 use helper classes to perform these behaviors for you.
14 A helper is simply a class. Let's say we want a helper named 'fooBar'.
15 By default, the class is prefixed with 'Zend_View_Helper_'
16 (you can specify a custom prefix when setting a helper path), and the
17 last segment of the class name is the helper name; this segment should
18 be TitleCapped; the full class name is then:
19 <classname>Zend_View_Helper_FooBar</classname>. This class should contain at the
20 minimum a single method, named after the helper, and camelCased:
21 <methodname>fooBar()</methodname>.
25 <title>Watch the Case</title>
27 Helper names are always camelCased, i.e., they never begin with an
28 uppercase character. The class name itself is MixedCased, but the
29 method that is actually executed is camelCased.
34 <title>Default Helper Path</title>
37 The default helper path always points to the Zend Framework view
38 helpers, i.e., 'Zend/View/Helper/'. Even if you call
39 <methodname>setHelperPath()</methodname> to overwrite the existing paths, this
40 path will be set to ensure the default helpers work.
45 To use a helper in your view script, call it using
46 <command>$this->helperName()</command>. Behind the scenes,
47 <classname>Zend_View</classname> will load the
48 <classname>Zend_View_Helper_HelperName</classname> class, create an object
49 instance of it, and call its <methodname>helperName()</methodname> method. The
50 object instance is persistent within the <classname>Zend_View</classname>
51 instance, and is reused for all future calls to
52 <command>$this->helperName()</command>.
55 <sect2 id="zend.view.helpers.initial">
56 <title>Initial Helpers</title>
59 <classname>Zend_View</classname> comes with an initial set of helper classes,
60 most of which relate to form element generation and perform
61 the appropriate output escaping automatically. In addition, there
62 are helpers for creating route-based <acronym>URL</acronym>s and HTML lists, as well as
63 declaring variables. The currently shipped helpers include:
69 <methodname>declareVars()</methodname>: Primarily for use when using
70 <methodname>strictVars()</methodname>, this helper can be used to declare
71 template variables that may or may not already be set in the
72 view object, as well as to set default values. Arrays passed as
73 arguments to the method will be used to set default values;
74 otherwise, if the variable does not exist, it is set to an empty
79 <methodname>fieldset($name, $content, $attribs)</methodname>: Creates an
80 <acronym>XHTML</acronym> fieldset. If <varname>$attribs</varname> contains a
81 'legend' key, that value will be used for the fieldset legend. The
82 fieldset will surround the <varname>$content</varname> as provided to
87 <methodname>form($name, $attribs, $content)</methodname>: Generates an
88 <acronym>XHTML</acronym> form. All <varname>$attribs</varname> are escaped and
89 rendered as <acronym>XHTML</acronym> attributes of the form tag. If
90 <varname>$content</varname> is present and not a boolean <constant>FALSE</constant>,
91 then that content is rendered within the start and close form tags; if
92 <varname>$content</varname> is a boolean <constant>FALSE</constant> (the default),
93 only the opening form tag is generated.
97 <methodname>formButton($name, $value, $attribs)</methodname>: Creates an
98 <button /> element.
103 <methodname>formCheckbox($name, $value, $attribs,
104 $options)</methodname>: Creates an <input type="checkbox"
109 By default, when no $value is provided and no $options are
110 present, '0' is assumed to be the unchecked value, and '1'
111 the checked value. If a $value is passed, but no $options
112 are present, the checked value is assumed to be the value
117 $options should be an array. If the array is indexed, the
118 first value is the checked value, and the second the
119 unchecked value; all other values are ignored. You may also
120 pass an associative array with the keys 'checked' and
125 If $options has been passed, if $value matches the checked
126 value, then the element will be marked as checked. You may
127 also mark the element as checked or unchecked by passing a
128 boolean value for the attribute 'checked'.
132 The above is probably best summed up with some examples:
135 <programlisting language="php"><![CDATA[
136 // '1' and '0' as checked/unchecked options; not checked
137 echo $this->formCheckbox('foo');
139 // '1' and '0' as checked/unchecked options; checked
140 echo $this->formCheckbox('foo', null, array('checked' => true));
142 // 'bar' and '0' as checked/unchecked options; not checked
143 echo $this->formCheckbox('foo', 'bar');
145 // 'bar' and '0' as checked/unchecked options; checked
146 echo $this->formCheckbox('foo', 'bar', array('checked' => true));
148 // 'bar' and 'baz' as checked/unchecked options; unchecked
149 echo $this->formCheckbox('foo', null, null, array('bar', 'baz'));
151 // 'bar' and 'baz' as checked/unchecked options; unchecked
152 echo $this->formCheckbox('foo', null, null, array(
157 // 'bar' and 'baz' as checked/unchecked options; checked
158 echo $this->formCheckbox('foo', 'bar', null, array('bar', 'baz'));
159 echo $this->formCheckbox('foo',
161 array('checked' => true),
162 array('bar', 'baz'));
164 // 'bar' and 'baz' as checked/unchecked options; unchecked
165 echo $this->formCheckbox('foo', 'baz', null, array('bar', 'baz'));
166 echo $this->formCheckbox('foo',
168 array('checked' => false),
169 array('bar', 'baz'));
173 In all cases, the markup prepends a hidden element with the
174 unchecked value; this way, if the value is unchecked, you
175 will still get a valid value returned to your form.
181 <methodname>formErrors($errors, $options)</methodname>: Generates an
182 <acronym>XHTML</acronym> unordered list to show errors.
183 <varname>$errors</varname> should be a string or an array of strings;
184 <varname>$options</varname> should be any attributes you want
185 placed in the opening list tag.
189 You can specify alternate opening, closing, and separator
190 content when rendering the errors by calling several methods
196 <methodname>setElementStart($string)</methodname>; default is
197 '<ul class="errors"%s"><li>', where %s
198 is replaced with the attributes as specified in
199 <varname>$options</varname>.
203 <methodname>setElementSeparator($string)</methodname>; default
204 is '</li><li>'.
208 <methodname>setElementEnd($string)</methodname>; default is
209 '</li></ul>'.
215 <methodname>formFile($name, $attribs)</methodname>: Creates an
216 <input type="file" /> element.
220 <methodname>formHidden($name, $value, $attribs)</methodname>: Creates an
221 <input type="hidden" /> element.
225 <methodname>formLabel($name, $value, $attribs)</methodname>: Creates a
226 <label> element, setting the <property>for</property> attribute to
227 <varname>$name</varname>, and the actual label text to
228 <varname>$value</varname>. If <emphasis>disable</emphasis> is passed in
229 <property>attribs</property>, nothing will be returned.
233 <methodname>formMultiCheckbox($name, $value, $attribs, $options,
234 $listsep)</methodname>: Creates a list of checkboxes.
235 <varname>$options</varname> should be an associative array, and may be
236 arbitrarily deep. <varname>$value</varname> may be a single value or
237 an array of selected values that match the keys in the
238 <varname>$options</varname> array. <varname>$listsep</varname> is an HTML
239 break ("<br />") by default. By default, this element is
240 treated as an array; all checkboxes share the same name, and are
241 submitted as an array.
245 <methodname>formPassword($name, $value, $attribs)</methodname>: Creates an
246 <input type="password" /> element.
250 <methodname>formRadio($name, $value, $attribs, $options)</methodname>:
251 Creates a series of <input type="radio" /> elements, one
252 for each of the $options elements. In the $options array, the
253 element key is the radio value, and the element value is the
254 radio label. The $value radio will be preselected for you.
258 <methodname>formReset($name, $value, $attribs)</methodname>: Creates an
259 <input type="reset" /> element.
263 <methodname>formSelect($name, $value, $attribs, $options)</methodname>:
264 Creates a <select>...</select> block, with one
265 <option>one for each of the $options elements. In the
266 $options array, the element key is the option value, and the
267 element value is the option label. The $value option(s) will be
272 <methodname>formSubmit($name, $value, $attribs)</methodname>: Creates an
273 <input type="submit" /> element.
277 <methodname>formText($name, $value, $attribs)</methodname>: Creates an
278 <input type="text" /> element.
282 <methodname>formTextarea($name, $value, $attribs)</methodname>: Creates a
283 <textarea>...</textarea> block.
287 <methodname>url($urlOptions, $name, $reset)</methodname>: Creates a
288 <acronym>URL</acronym> string based on a named route.
289 <varname>$urlOptions</varname> should be an associative array of key/value pairs
290 used by the particular route.
294 <methodname>htmlList($items, $ordered, $attribs, $escape)</methodname>: generates
295 unordered and ordered lists based on the <varname>$items</varname>
296 passed to it. If <varname>$items</varname> is a multidimensional
297 array, a nested list will be built. If the <varname>$escape</varname>
298 flag is <constant>TRUE</constant> (default), individual items will be escaped using
299 the view objects registered escaping mechanisms; pass a <constant>FALSE</constant>
300 value if you want to allow markup in your lists.
306 Using these in your view scripts is very easy, here is an example.
307 Note that you all you need to do is call them; they will load
308 and instantiate themselves as they are needed.
311 <programlisting language="php"><![CDATA[
312 // inside your view script, $this refers to the Zend_View instance.
314 // say that you have already assigned a series of select options under
315 // the name $countries as array('us' => 'United States', 'il' =>
316 // 'Israel', 'de' => 'Germany').
318 <form action="action.php" method="post">
319 <p><label>Your Email:
320 <?php echo $this->formText('email', 'you@example.com', array('size' => 32)) ?>
322 <p><label>Your Country:
323 <?php echo $this->formSelect('country', 'us', null, $this->countries) ?>
325 <p><label>Would you like to opt in?
326 <?php echo $this->formCheckbox('opt_in', 'yes', null, array('yes', 'no')) ?>
332 The resulting output from the view script will look something like this:
335 <programlisting language="php"><![CDATA[
336 <form action="action.php" method="post">
337 <p><label>Your Email:
338 <input type="text" name="email" value="you@example.com" size="32" />
340 <p><label>Your Country:
341 <select name="country">
342 <option value="us" selected="selected">United States</option>
343 <option value="il">Israel</option>
344 <option value="de">Germany</option>
347 <p><label>Would you like to opt in?
348 <input type="hidden" name="opt_in" value="no" />
349 <input type="checkbox" name="opt_in" value="yes" checked="checked" />
354 <xi:include href="Zend_View-Helpers-Action.xml" />
355 <xi:include href="Zend_View-Helpers-BaseUrl.xml" />
356 <xi:include href="Zend_View-Helpers-Currency.xml" />
357 <xi:include href="Zend_View-Helpers-Cycle.xml" />
358 <xi:include href="Zend_View-Helpers-Partial.xml" />
359 <xi:include href="Zend_View-Helpers-Placeholder.xml" />
360 <xi:include href="Zend_View-Helpers-Doctype.xml" />
361 <xi:include href="Zend_View-Helpers-HeadLink.xml" />
362 <xi:include href="Zend_View-Helpers-HeadMeta.xml" />
363 <xi:include href="Zend_View-Helpers-HeadScript.xml" />
364 <xi:include href="Zend_View-Helpers-HeadStyle.xml" />
365 <xi:include href="Zend_View-Helpers-HeadTitle.xml" />
366 <xi:include href="Zend_View-Helpers-HtmlObject.xml" />
367 <xi:include href="Zend_View-Helpers-InlineScript.xml" />
368 <xi:include href="Zend_View-Helpers-Json.xml" />
369 <xi:include href="Zend_View-Helpers-Navigation.xml" />
370 <xi:include href="Zend_View-Helpers-Translate.xml" />
373 <sect2 id="zend.view.helpers.paths">
374 <title>Helper Paths</title>
377 As with view scripts, your controller can specify a stack of paths
378 for <classname>Zend_View</classname> to search for helper classes. By default,
379 <classname>Zend_View</classname> looks in "Zend/View/Helper/*" for helper
380 classes. You can tell <classname>Zend_View</classname> to look in other
381 locations using the <methodname>setHelperPath()</methodname> and
382 <methodname>addHelperPath()</methodname> methods. Additionally, you can
383 indicate a class prefix to use for helpers in the path provided, to
384 allow namespacing your helper classes. By default, if no class
385 prefix is provided, 'Zend_View_Helper_' is assumed.
388 <programlisting language="php"><![CDATA[
389 $view = new Zend_View();
391 // Set path to /path/to/more/helpers, with prefix 'My_View_Helper'
392 $view->setHelperPath('/path/to/more/helpers', 'My_View_Helper');
396 In fact, you can "stack" paths using the
397 <methodname>addHelperPath()</methodname> method. As you add paths to the stack,
398 <classname>Zend_View</classname> will look at the most-recently-added path for
399 the requested helper class. This allows you to add to (or even
400 override) the initial distribution of helpers with your own custom
404 <programlisting language="php"><![CDATA[
405 $view = new Zend_View();
406 // Add /path/to/some/helpers with class prefix 'My_View_Helper'
407 $view->addHelperPath('/path/to/some/helpers', 'My_View_Helper');
408 // Add /other/path/to/helpers with class prefix 'Your_View_Helper'
409 $view->addHelperPath('/other/path/to/helpers', 'Your_View_Helper');
411 // now when you call $this->helperName(), Zend_View will look first for
412 // "/path/to/some/helpers/HelperName" using class name
413 // "Your_View_Helper_HelperName", then for
414 // "/other/path/to/helpers/HelperName.php" using class name
415 // "My_View_Helper_HelperName", and finally for
416 // "Zend/View/Helper/HelperName.php" using class name
417 // "Zend_View_Helper_HelperName".
422 <sect2 id="zend.view.helpers.custom">
423 <title>Writing Custom Helpers</title>
426 Writing custom helpers is easy; just follow these rules:
432 While not strictly necessary, we recommend either implementing
433 <classname>Zend_View_Helper_Interface</classname> or extending
434 <classname>Zend_View_Helper_Abstract</classname> when creating your
435 helpers. Introduced in 1.6.0, these simply define a
436 <methodname>setView()</methodname> method; however, in upcoming releases, we
437 plan to implement a strategy pattern that will simplify much of
438 the naming schema detailed below. Building off these now will
439 help you future-proof your code.
443 The class name must, at the very minimum, end with the helper
444 name itself, using MixedCaps. E.g., if you were writing a
445 helper called "specialPurpose", the class name would minimally
446 need to be "SpecialPurpose". You may, and should, give the class
447 name a prefix, and it is recommended that you use 'View_Helper'
448 as part of that prefix: "My_View_Helper_SpecialPurpose". (You
449 will need to pass in the prefix, with or without the trailing
450 underscore, to <methodname>addHelperPath()</methodname> or
451 <methodname>setHelperPath()</methodname>).
455 The class must have a public method that matches the
456 helper name; this is the method that will be called when
457 your template calls "$this->specialPurpose()". In our
458 "specialPurpose" helper example, the required method
459 declaration would be "public function specialPurpose()".
463 In general, the class should not echo or print or otherwise
464 generate output. Instead, it should return values to be
465 printed or echoed. The returned values should be escaped
470 The class must be in a file named after the helper class. Again
471 using our "specialPurpose" helper example, the file has to be
472 named "SpecialPurpose.php".
477 Place the helper class file somewhere in your helper path stack, and
478 <classname>Zend_View</classname> will automatically load, instantiate,
479 persist, and execute it for you.
483 Here is an example of our <classname>SpecialPurpose</classname> helper code:
486 <programlisting language="php"><![CDATA[
487 class My_View_Helper_SpecialPurpose extends Zend_View_Helper_Abstract
489 protected $_count = 0;
490 public function specialPurpose()
493 $output = "I have seen 'The Jerk' {$this->_count} time(s).";
494 return htmlspecialchars($output);
500 Then in a view script, you can call the <classname>SpecialPurpose</classname>
501 helper as many times as you like; it will be instantiated once, and
502 then it persists for the life of that <classname>Zend_View</classname>
506 <programlisting language="php"><![CDATA[
507 // remember, in a view script, $this refers to the Zend_View instance.
508 echo $this->specialPurpose();
509 echo $this->specialPurpose();
510 echo $this->specialPurpose();
514 The output would look something like this:
516 <programlisting language="php"><![CDATA[
517 I have seen 'The Jerk' 1 time(s).
518 I have seen 'The Jerk' 2 time(s).
519 I have seen 'The Jerk' 3 time(s).
523 Sometimes you will need access to the calling <classname>Zend_View</classname>
524 object -- for instance, if you need to use the registered encoding,
525 or want to render another view script as part of your helper. To get
526 access to the view object, your helper class should have a
527 <methodname>setView($view)</methodname> method, like the following:
530 <programlisting language="php"><![CDATA[
531 class My_View_Helper_ScriptPath
535 public function setView(Zend_View_Interface $view)
540 public function scriptPath($script)
542 return $this->view->getScriptPath($script);
548 If your helper class has a <methodname>setView()</methodname> method, it will be
549 called when the helper class is first instantiated, and passed the
550 current view object. It is up to you to persist the object in your
551 class, as well as determine how it should be accessed.
555 If you are extending <classname>Zend_View_Helper_Abstract</classname>, you do
556 not need to define this method, as it is defined for you.
560 <sect2 id="zend.view.helpers.registering-concrete">
561 <title>Registering Concrete Helpers</title>
564 Sometimes it is convenient to instantiate a view helper, and then register it with the
565 view. As of version 1.10.0, this is now possible using the
566 <methodname>registerHelper()</methodname> method, which expects two arguments: the
567 helper object, and the name by which it will be registered.
570 <programlisting language="php"><![CDATA[
571 $helper = new My_Helper_Foo();
572 // ...do some configuration or dependency injection...
574 $view->registerHelper($helper, 'foo');
578 If the helper has a <methodname>setView()</methodname> method, the view object will call
579 this and inject itself into the helper on registration.
583 <title>Helper name should match a method</title>
586 The second argument to <methodname>registerHelper()</methodname> is the name of the
587 helper. A corresponding method name should exist in the helper; otherwise,
588 <classname>Zend_View</classname> will call a non-existent method when invoking the
589 helper, raising a fatal PHP error.