Previous Next

View Helpers

In your view scripts, often it is necessary to perform certain complex functions over and over: e.g., formatting a date, generating form elements, or displaying action links. You can use helper classes to perform these behaviors for you.

A helper is simply a class. Let's say we want a helper named 'fooBar'. By default, the class is prefixed with 'Zend_View_Helper_' (you can specify a custom prefix when setting a helper path), and the last segment of the class name is the helper name; this segment should be TitleCapped; the full class name is then: Zend_View_Helper_FooBar. This class should contain at the minimum a single method, named after the helper, and camelCased: fooBar().

Note: Watch the Case

Helper names are always camelCased, i.e., they never begin with an uppercase character. The class name itself is MixedCased, but the method that is actually executed is camelCased.

Note: Default Helper Path

The default helper path always points to the Zend Framework view helpers, i.e., 'Zend/View/Helper/'. Even if you call setHelperPath() to overwrite the existing paths, this path will be set to ensure the default helpers work.

To use a helper in your view script, call it using $this->helperName(). Behind the scenes, Zend_View will load the Zend_View_Helper_HelperName class, create an object instance of it, and call its helperName() method. The object instance is persistent within the Zend_View instance, and is reused for all future calls to $this->helperName().

Initial Helpers

Zend_View comes with an initial set of helper classes, most of which relate to form element generation and perform the appropriate output escaping automatically. In addition, there are helpers for creating route-based URLs and HTML lists, as well as declaring variables. The currently shipped helpers include:

  • declareVars(): Primarily for use when using strictVars(), this helper can be used to declare template variables that may or may not already be set in the view object, as well as to set default values. Arrays passed as arguments to the method will be used to set default values; otherwise, if the variable does not exist, it is set to an empty string.

  • fieldset($name, $content, $attribs): Creates an XHTML fieldset. If $attribs contains a 'legend' key, that value will be used for the fieldset legend. The fieldset will surround the $content as provided to the helper.

  • form($name, $attribs, $content): Generates an XHTML form. All $attribs are escaped and rendered as XHTML attributes of the form tag. If $content is present and not a boolean false, then that content is rendered within the start and close form tags; if $content is a boolean false (the default), only the opening form tag is generated.

  • formButton($name, $value, $attribs): Creates an <button /> element.

  • formCheckbox($name, $value, $attribs, $options): Creates an <input type="checkbox" /> element.

    By default, when no $value is provided and no $options are present, '0' is assumed to be the unchecked value, and '1' the checked value. If a $value is passed, but no $options are present, the checked value is assumed to be the value passed.

    $options should be an array. If the array is indexed, the first value is the checked value, and the second the unchecked value; all other values are ignored. You may also pass an associative array with the keys 'checked' and 'unChecked'.

    If $options has been passed, if $value matches the checked value, then the element will be marked as checked. You may also mark the element as checked or unchecked by passing a boolean value for the attribute 'checked'.

    The above is probably best summed up with some examples:

    // '1' and '0' as checked/unchecked options; not checked
    echo $this->formCheckbox('foo');
    
    // '1' and '0' as checked/unchecked options; checked
    echo $this->formCheckbox('foo', null, array('checked' => true));
    
    // 'bar' and '0' as checked/unchecked options; not checked
    echo $this->formCheckbox('foo', 'bar');
    
    // 'bar' and '0' as checked/unchecked options; checked
    echo $this->formCheckbox('foo', 'bar', array('checked' => true));
    
    // 'bar' and 'baz' as checked/unchecked options; unchecked
    echo $this->formCheckbox('foo', null, null, array('bar', 'baz');
    
    // 'bar' and 'baz' as checked/unchecked options; unchecked
    echo $this->formCheckbox('foo', null, null, array(
        'checked' => 'bar',
        'unChecked' => 'baz'
    ));
    
    // 'bar' and 'baz' as checked/unchecked options; checked
    echo $this->formCheckbox('foo', 'bar', null, array('bar', 'baz');
    echo $this->formCheckbox('foo',
                             null,
                             array('checked' => true),
                             array('bar', 'baz');
    
    // 'bar' and 'baz' as checked/unchecked options; unchecked
    echo $this->formCheckbox('foo', 'baz', null, array('bar', 'baz');
    echo $this->formCheckbox('foo',
                             null,
                             array('checked' => false),
                             array('bar', 'baz');

    In all cases, the markup prepends a hidden element with the unchecked value; this way, if the value is unchecked, you will still get a valid value returned to your form.

  • formErrors($errors, $options): Generates an XHTML unordered list to show errors. $errors should be a string or an array of strings; $options should be any attributes you want placed in the opening list tag.

    You can specify alternate opening, closing, and separator content when rendering the errors by calling several methods on the helper:

    • setElementStart($string); default is '<ul class="errors"%s"><li>', where %s is replaced with the attributes as specified in $options.

    • setElementSeparator($string); default is '</li><li>'.

    • setElementEnd($string); default is '</li></ul>'.

  • formFile($name, $attribs): Creates an <input type="file" /> element.

  • formHidden($name, $value, $attribs): Creates an <input type="hidden" /> element.

  • formLabel($name, $value, $attribs): Creates a <label> element, setting the for attribute to $name, and the actual label text to $value. If disable is passed in attribs, nothing will be returned.

  • formMultiCheckbox($name, $value, $attribs, $options, $listsep): Creates a list of checkboxes. $options should be an associative array, and may be arbitrarily deep. $value may be a single value or an array of selected values that match the keys in the $options array. $listsep is an HTML break ("<br />") by default. By default, this element is treated as an array; all checkboxes share the same name, and are submitted as an array.

  • formPassword($name, $value, $attribs): Creates an <input type="password" /> element.

  • formRadio($name, $value, $attribs, $options): Creates a series of <input type="radio" /> elements, one for each of the $options elements. In the $options array, the element key is the radio value, and the element value is the radio label. The $value radio will be preselected for you.

  • formReset($name, $value, $attribs): Creates an <input type="reset" /> element.

  • formSelect($name, $value, $attribs, $options): Creates a <select>...</select> block, with one <option>one for each of the $options elements. In the $options array, the element key is the option value, and the element value is the option label. The $value option(s) will be preselected for you.

  • formSubmit($name, $value, $attribs): Creates an <input type="submit" /> element.

  • formText($name, $value, $attribs): Creates an <input type="text" /> element.

  • formTextarea($name, $value, $attribs): Creates a <textarea>...</textarea> block.

  • url($urlOptions, $name, $reset): Creates a URL string based on a named route. $urlOptions should be an associative array of key/value pairs used by the particular route.

  • htmlList($items, $ordered, $attribs, $escape): generates unordered and ordered lists based on the $items passed to it. If $items is a multidimensional array, a nested list will be built. If the $escape flag is true (default), individual items will be escaped using the view objects registered escaping mechanisms; pass a false value if you want to allow markup in your lists.

Using these in your view scripts is very easy, here is an example. Note that you all you need to do is call them; they will load and instantiate themselves as they are needed.

// inside your view script, $this refers to the Zend_View instance.
//
// say that you have already assigned a series of select options under
// the name $countries as array('us' => 'United States', 'il' =>
// 'Israel', 'de' => 'Germany').
?>

The resulting output from the view script will look something like this:

Action View Helper

The Action view helper enables view scripts to dispatch a given controller action; the result of the response object following the dispatch is then returned. These can be used when a particular action could generate re-usable content or "widget-ized" content.

Actions that result in a _forward() or redirect are considered invalid, and will return an empty string.

The API for the Action view helper follows that of most MVC components that invoke controller actions: action($action, $controller, $module = null, array $params = array()). $action and $controller are required; if no module is specified, the default module is assumed.

Example #1 Basic Usage of Action View Helper

As an example, you may have a CommentController with a listAction() method you wish to invoke in order to pull a list of comments for the current request:

Partial Helper

The Partial view helper is used to render a specified template within its own variable scope. The primary use is for reusable template fragments with which you do not need to worry about variable name clashes. Additionally, they allow you to specify partial view scripts from specific modules.

A sibling to the Partial, the PartialLoop view helper allows you to pass iterable data, and render a partial for each item.

Note: PartialLoop Counter

The PartialLoop view helper assigns a variable to the view named partialCounter which passes the current position of the array to the view script. This provides an easy way to have alternating colors on table rows for example.

Example #2 Basic Usage of Partials

Basic usage of partials is to render a template fragment in its own view scope. Consider the following partial script:


  • From: escape($this->from) ?>
  • Subject: escape($this->subject) ?>

You would then call it from your view script using the following:

partial('partial.phtml', array(
    'from' => 'Team Framework',
    'subject' => 'view partials')); ?>

Which would then render:

  • From: Team Framework
  • Subject: view partials

Note: What is a model?

A model used with the Partial view helper can be one of the following:

  • Array. If an array is passed, it should be associative, as its key/value pairs are assigned to the view with keys as view variables.

  • Object implementing toArray() method. If an object is passed an has a toArray() method, the results of toArray() will be assigned to the view object as view variables.

  • Standard object. Any other object will assign the results of object_get_vars() (essentially all public properties of the object) to the view object.

If your model is an object, you may want to have it passed as an object to the partial script, instead of serializing it to an array of variables. You can do this by setting the 'objectKey' property of the appropriate helper:

// Tell partial to pass objects as 'model' variable
$view->partial()->setObjectKey('model');

// Tell partial to pass objects from partialLoop as 'model' variable
// in final partial view script:
$view->partialLoop()->setObjectKey('model');

This technique is particularly useful when passing Zend_Db_Table_Rowsets to partialLoop(), as you then have full access to your row objects within the view scripts, allowing you to call methods on them (such as retrieving values from parent or dependent rows).

Example #3 Using PartialLoop to Render Iterable Models

Typically, you'll want to use partials in a loop, to render the same content fragment many times; this way you can put large blocks of repeated content or complex display logic into a single location. However this has a performance impact, as the partial helper needs to be invoked once for each iteration.

The PartialLoop view helper helps solve this issue. It allows you to pass an iterable item (array or object implementing Iterator) as the model. It then iterates over this, passing, the items to the partial script as the model. Items in the iterator may be any model the Partial view helper allows.

Let's assume the following partial view script:


    
key ?>
value ?>

And the following "model":

$model = array(
    array('key' => 'Mammal', 'value' => 'Camel'),
    array('key' => 'Bird', 'value' => 'Penguin'),
    array('key' => 'Reptile', 'value' => 'Asp'),
    array('key' => 'Fish', 'value' => 'Flounder'),
);

In your view script, you could then invoke the PartialLoop helper:

partialLoop('partialLoop.phtml', $model) ?>
Mammal
Camel
Bird
Penguin
Reptile
Asp
Fish
Flounder

Example #4 Rendering Partials in Other Modules

Sometime a partial will exist in a different module. If you know the name of the module, you can pass it as the second argument to either partial() or partialLoop(), moving the $model argument to third position.

For instance, if there's a pager partial you wish to use that's in the 'list' module, you could grab it as follows:

partial('pager.phtml', 'list', $pagerData) ?>

In this way, you can re-use partials created specifically for other modules. That said, it's likely a better practice to put re-usable partials in shared view script paths.

Placeholder Helper

The Placeholder view helper is used to persist content between view scripts and view instances. It also offers some useful features such as aggregating content, capturing view script content for later use, and adding pre- and post-text to content (and custom separators for aggregated content).

Example #5 Basic Usage of Placeholders

Basic usage of placeholders is to persist view data. Each invocation of the Placeholder helper expects a placeholder name; the helper then returns a placeholder container object that you can either manipulate or simply echo out.

placeholder('foo')->set("Some text for later") ?>

placeholder('foo');
    // outputs "Some text for later"
?>

Example #6 Using Placeholders to Aggregate Content

Aggregating content via placeholders can be useful at times as well. For instance, your view script may have a variable array from which you wish to retrieve messages to display later; a later view script can then determine how those will be rendered.

The Placeholder view helper uses containers that extend ArrayObject, providing a rich featureset for manipulating arrays. In addition, it offers a variety of methods for formatting the content stored in the container:

  • setPrefix($prefix) sets text with which to prefix the content. Use getPrefix() at any time to determine what the current setting is.

  • setPostfix($prefix) sets text with which to append the content. Use getPostfix() at any time to determine what the current setting is.

  • setSeparator($prefix) sets text with which to separate aggregated content. Use getSeparator() at any time to determine what the current setting is.

  • setIndent($prefix) can be used to set an indentation value for content. If an integer is passed, that number of spaces will be used; if a string is passed, the string will be used. Use getIndent() at any time to determine what the current setting is.


placeholder('foo')->exchangeArray($this->data) ?>

placeholder('foo')->setPrefix("
    \n
  • ") ->setSeparator("
  • \n") ->setIndent(4) ->setPostfix("
\n"); ?> placeholder('foo'); // outputs as unordered list with pretty indentation ?>

Because the Placeholder container objects extend ArrayObject, you can also assign content to a specific key in the container easily, instead of simply pushing it into the container. Keys may be accessed either as object properties or as array keys.

placeholder('foo')->bar = $this->data ?>
placeholder('foo')->bar ?>

placeholder('foo');
echo $foo['bar'];
?>

Example #7 Using Placeholders to Capture Content

Occasionally you may have content for a placeholder in a view script that is easiest to template; the Placeholder view helper allows you to capture arbitrary content for later rendering using the following API.

  • captureStart($type, $key) begins capturing content.

    $type should be one of the Placeholder constants APPEND or SET. If APPEND, captured content is appended to the list of current content in the placeholder; if SET, captured content is used as the sole value of the placeholder (potentially replacing any previous content). By default, $type is APPEND.

    $key can be used to specify a specific key in the placeholder container to which you want content captured.

    captureStart() locks capturing until captureEnd() is called; you cannot nest capturing with the same placeholder container. Doing so will raise an exception.

  • captureEnd() stops capturing content, and places it in the container object according to how captureStart() was called.


placeholder('foo')->captureStart();
foreach ($this->data as $datum): ?>

title ?>

content ?>

placeholder('foo')->captureEnd() ?> placeholder('foo') ?>

placeholder('foo')->captureStart('SET', 'data');
foreach ($this->data as $datum): ?>

title ?>

content ?>

placeholder('foo')->captureEnd() ?> placeholder('foo')->data ?>

Concrete Placeholder Implementations

Zend Framework ships with a number of "concrete" placeholder implementations. These are for commonly used placeholders: doctype, page title, and various <head> elements. In all cases, calling the placeholder with no arguments returns the element itself.

Documentation for each element is covered separately, as linked below:

Doctype Helper

Valid HTML and XHTML documents should include a DOCTYPE declaration. Besides being difficult to remember, these can also affect how certain elements in your document should be rendered (for instance, CDATA escaping in <script> and <style> elements.

The Doctype helper allows you to specify one of the following types:

  • XHTML11

  • XHTML1_STRICT

  • XHTML1_TRANSITIONAL

  • XHTML1_FRAMESET

  • XHTML_BASIC1

  • HTML4_STRICT

  • HTML4_LOOSE

  • HTML4_FRAMESET

  • HTML5

You can also specify a custom doctype as long as it is well-formed.

The Doctype helper is a concrete implementation of the Placeholder helper.

Example #8 Doctype Helper Basic Usage

You may specify the doctype at any time. However, helpers that depend on the doctype for their output will recognize it only after you have set it, so the easiest approach is to specify it in your bootstrap:

$doctypeHelper = new Zend_View_Helper_Doctype();
$doctypeHelper->doctype('XHTML1_STRICT');

And then print it out on top of your layout script:

doctype() ?>

Example #9 Retrieving the Doctype

If you need to know the doctype, you can do so by calling getDoctype() on the object, which is returned by invoking the helper.

$doctype = $view->doctype()->getDoctype();

Typically, you'll simply want to know if the doctype is XHTML or not; for this, the isXhtml() method will suffice:

if ($view->doctype()->isXhtml()) {
    // do something differently
}

HeadMeta Helper

The HTML <meta> element is used to provide meta information about your HTML document -- typically keywords, document character set, caching pragmas, etc. Meta tags may be either of the 'http-equiv' or 'name' types, must contain a 'content' attribute, and can also have either of the 'lang' or 'scheme' modifier attributes.

The HeadMeta helper supports the following methods for setting and adding meta tags:

  • appendName($keyValue, $content, $conditionalName)

  • offsetSetName($index, $keyValue, $content, $conditionalName)

  • prependName($keyValue, $content, $conditionalName)

  • setName($keyValue, $content, $modifiers)

  • appendHttpEquiv($keyValue, $content, $conditionalHttpEquiv)

  • offsetSetHttpEquiv($index, $keyValue, $content, $conditionalHttpEquiv)

  • prependHttpEquiv($keyValue, $content, $conditionalHttpEquiv)

  • setHttpEquiv($keyValue, $content, $modifiers)

The $keyValue item is used to define a value for the 'name' or 'http-equiv' key; $content is the value for the 'content' key, and $modifiers is an optional associative array that can contain keys for 'lang' and/or 'scheme'.

You may also set meta tags using the headMeta() helper method, which has the following signature: headMeta($content, $keyValue, $keyType = 'name', $modifiers = array(), $placement = 'APPEND'). $keyValue is the content for the key specified in $keyType, which should be either 'name' or 'http-equiv'. $placement can be either 'SET' (overwrites all previously stored values), 'APPEND' (added to end of stack), or 'PREPEND' (added to top of stack).

HeadMeta overrides each of append(), offsetSet(), prepend(), and set() to enforce usage of the special methods as listed above. Internally, it stores each item as a stdClass token, which it later serializes using the itemToString() method. This allows you to perform checks on the items in the stack, and optionally modify these items by simply modifying the object returned.

The HeadMeta helper is a concrete implementation of the Placeholder helper.

Example #11 HeadMeta Helper Basic Usage

You may specify a new meta tag at any time. Typically, you will specify client-side caching rules or SEO keywords.

For instance, if you wish to specify SEO keywords, you'd be creating a meta name tag with the name 'keywords' and the content the keywords you wish to associate with your page:

// setting meta keywords
$this->headMeta()->appendName('keywords', 'framework php productivity');

If you wished to set some client-side caching rules, you'd set http-equiv tags with the rules you wish to enforce:

// disabling client-side cache
$this->headMeta()->appendHttpEquiv('expires',
                                   'Wed, 26 Feb 1997 08:21:57 GMT')
                 ->appendHttpEquiv('pragma', 'no-cache')
                 ->appendHttpEquiv('Cache-Control', 'no-cache');

Another popular use for meta tags is setting the content type, character set, and language:

// setting content type and character set
$this->headMeta()->appendHttpEquiv('Content-Type',
                                   'text/html; charset=UTF-8')
                 ->appendHttpEquiv('Content-Language', 'en-US');

As a final example, an easy way to display a transitional message before a redirect is using a "meta refresh":

// setting a meta refresh for 3 seconds to a new url:
$this->headMeta()->appendHttpEquiv('Refresh',
                                   '3;URL=http://www.some.org/some.html');

When you're ready to place your meta tags in the layout, simply echo the helper:

headMeta() ?>

HeadScript Helper

The HTML <script> element is used to either provide inline client-side scripting elements or link to a remote resource containing client-side scripting code. The HeadScript helper allows you to manage both.

The HeadScript helper supports the following methods for setting and adding scripts:

  • appendFile($src, $type = 'text/javascript', $attrs = array())

  • offsetSetFile($index, $src, $type = 'text/javascript', $attrs = array())

  • prependFile($src, $type = 'text/javascript', $attrs = array())

  • setFile($src, $type = 'text/javascript', $attrs = array())

  • appendScript($script, $type = 'text/javascript', $attrs = array())

  • offsetSetScript($index, $script, $type = 'text/javascript', $attrs = array())

  • prependScript($script, $type = 'text/javascript', $attrs = array())

  • setScript($script, $type = 'text/javascript', $attrs = array())

In the case of the *File() methods, $src is the remote location of the script to load; this is usually in the form of a URL or a path. For the *Script() methods, $script is the client-side scripting directives you wish to use in the element.

Note: Setting Conditional Comments

HeadScript allows you to wrap the script tag in conditional comments, which allows you to hide them from specific browsers. To add set the conditional tags, pass the conditional value as part of the $attrs parameter in the method calls.

// adding scripts
$this->headScript()->appendFile('/js/prototype.js', 'text/javascript', array('conditional' => 'lt IE 7');

HeadScript also allows capturing scripts; this can be useful if you want to create the client-side script programmatically, and then place it elsewhere. The usage for this will be showed in an example below.

Finally, you can also use the headScript() method to quickly add script elements; the signature for this is headScript($mode = 'FILE', $spec, $placement = 'APPEND'). The $mode is either 'FILE' or 'SCRIPT', depending on if you're linking a script or defining one. $spec is either the script file to link or the script source itself. $placement should be either 'APPEND', 'PREPEND', or 'SET'.

HeadScript overrides each of append(), offsetSet(), prepend(), and set() to enforce usage of the special methods as listed above. Internally, it stores each item as a stdClass token, which it later serializes using the itemToString() method. This allows you to perform checks on the items in the stack, and optionally modify these items by simply modifying the object returned.

The HeadScript helper is a concrete implementation of the Placeholder helper.

Note: Use InlineScript for HTML Body Scripts

HeadScript's sibling helper, InlineScript, should be used when you wish to include scripts inline in the HTML body. Placing scripts at the end of your document is a good practice for speeding up delivery of your page, particularly when using 3rd party analytics scripts.

Note: Arbitrary Attributes are Disabled by Default

By default, HeadScript only will render <script> attributes that are blessed by the W3C. These include 'type', 'charset', 'defer', 'language', and 'src'. However, some javascript frameworks, notably » Dojo, utilize custom attributes in order to modify behavior. To allow such attributes, you can enable them via the setAllowArbitraryAttributes() method:

$this->headScript()->setAllowArbitraryAttributes(true);

Example #12 HeadScript Helper Basic Usage

You may specify a new script tag at any time. As noted above, these may be links to outside resource files or scripts themselves.

// adding scripts
$this->headScript()->appendFile('/js/prototype.js')
                   ->appendScript($onloadScript);

Order is often important with client-side scripting; you may need to ensure that libraries are loaded in a specific order due to dependencies each have; use the various append, prepend, and offsetSet directives to aid in this task:

// Putting scripts in order

// place at a particular offset to ensure loaded last
$this->headScript()->offsetSetFile(100, '/js/myfuncs.js');

// use scriptaculous effects (append uses next index, 101)
$this->headScript()->appendFile('/js/scriptaculous.js');

// but always have base prototype script load first:
$this->headScript()->prependFile('/js/prototype.js');

When you're finally ready to output all scripts in your layout script, simply echo the helper:

headScript() ?>

Example #13 Capturing Scripts Using the HeadScript Helper

Sometimes you need to generate client-side scripts programmatically. While you could use string concatenation, heredocs, and the like, often it's easier just to do so by creating the script and sprinkling in PHP tags. HeadScript lets you do just that, capturing it to the stack:

headScript()->captureStart() ?>
var action = 'baseUrl ?>';
$('foo_form').action = action;
headScript()->captureEnd() ?>

The following assumptions are made:

  • The script will be appended to the stack. If you wish for it to replace the stack or be added to the top, you will need to pass 'SET' or 'PREPEND', respectively, as the first argument to captureStart().

  • The script MIME type is assumed to be 'text/javascript'; if you wish to specify a different type, you will need to pass it as the second argument to captureStart().

  • If you wish to specify any additional attributes for the <script> tag, pass them in an array as the third argument to captureStart().

HeadStyle Helper

The HTML <style> element is used to include CSS stylesheets inline in the HTML <head> element.

Note: Use HeadLink to link CSS files

HeadLink should be used to create <link> elements for including external stylesheets. HeadScript is used when you wish to define your stylesheets inline.

The HeadStyle helper supports the following methods for setting and adding stylesheet declarations:

  • appendStyle($content, $attributes = array())

  • offsetSetStyle($index, $content, $attributes = array())

  • prependStyle($content, $attributes = array())

  • setStyle($content, $attributes = array())

In all cases, $content is the actual CSS declarations. $attributes are any additional attributes you wish to provide to the style tag: lang, title, media, or dir are all permissible.

Note: Setting Conditional Comments

HeadStyle allows you to wrap the style tag in conditional comments, which allows you to hide them from specific browsers. To add set the conditional tags, pass the conditional value as part of the $attributes parameter in the method calls.

// adding scripts
$this->headStyle()->appendStyle($styles, array('conditional' => 'lt IE 7');

HeadStyle also allows capturing style declarations; this can be useful if you want to create the declarations programmatically, and then place them elsewhere. The usage for this will be showed in an example below.

Finally, you can also use the headStyle() method to quickly add declarations elements; the signature for this is headStyle($content$placement = 'APPEND', $attributes = array()). $placement should be either 'APPEND', 'PREPEND', or 'SET'.

HeadStyle overrides each of append(), offsetSet(), prepend(), and set() to enforce usage of the special methods as listed above. Internally, it stores each item as a stdClass token, which it later serializes using the itemToString() method. This allows you to perform checks on the items in the stack, and optionally modify these items by simply modifying the object returned.

The HeadStyle helper is a concrete implementation of the Placeholder helper.

Example #14 HeadStyle Helper Basic Usage

You may specify a new style tag at any time:

// adding styles
$this->headStyle()->appendStyle($styles);

Order is very important with CSS; you may need to ensure that declarations are loaded in a specific order due to the order of the cascade; use the various append, prepend, and offsetSet directives to aid in this task:

// Putting styles in order

// place at a particular offset:
$this->headStyle()->offsetSetStyle(100, $customStyles);

// place at end:
$this->headStyle()->appendStyle($finalStyles);

// place at beginning
$this->headStyle()->prependStyle($firstStyles);

When you're finally ready to output all style declarations in your layout script, simply echo the helper:

headStyle() ?>

Example #15 Capturing Style Declarations Using the HeadStyle Helper

Sometimes you need to generate CSS style declarations programmatically. While you could use string concatenation, heredocs, and the like, often it's easier just to do so by creating the styles and sprinkling in PHP tags. HeadStyle lets you do just that, capturing it to the stack:

headStyle()->captureStart() ?>
body {
    background-color: bgColor ?>;
}
headStyle()->captureEnd() ?>

The following assumptions are made:

  • The style declarations will be appended to the stack. If you wish for them to replace the stack or be added to the top, you will need to pass 'SET' or 'PREPEND', respectively, as the first argument to captureStart().

  • If you wish to specify any additional attributes for the <style> tag, pass them in an array as the second argument to captureStart().

HeadTitle Helper

The HTML <title> element is used to provide a title for an HTML document. The HeadTitle helper allows you to programmatically create and store the title for later retrieval and output.

The HeadTitle helper is a concrete implementation of the Placeholder helper. It overrides the toString() method to enforce generating a <title> element, and adds a headTitle() method for quick and easy setting and aggregation of title elements. The signature for that method is headTitle($title, $setType = 'APPEND'); by default, the value is appended to the stack (aggregating title segments), but you may also specify either 'PREPEND' (place at top of stack) or 'SET' (overwrite stack).

Example #16 HeadTitle Helper Basic Usage

You may specify a title tag at any time. A typical usage would have you setting title segments for each level of depth in your application: site, controller, action, and potentially resource.

// setting the controller and action name as title segments:
$request = Zend_Controller_Front::getInstance()->getRequest();
$this->headTitle($request->getActionName())
     ->headTitle($request->getControllerName());

// setting the site in the title; possibly in the layout script:
$this->headTitle('Zend Framework');

// setting a separator string for segments:
$this->headTitle()->setSeparator(' / ');

When you're finally ready to render the title in your layout script, simply echo the helper:


headTitle() ?>

HTML Object Helpers

The HTML <object> element is used for embedding media like Flash or QuickTime in web pages. The object view helpers take care of embedding media with minimum effort.

There are four initial Object helpers:

  • formFlash Generates markup for embedding Flash files.

  • formObject Generates markup for embedding a custom Object.

  • formPage Generates markup for embedding other (X)HTML pages.

  • formQuicktime Generates markup for embedding QuickTime files.

All of these helpers share a similar interface. For this reason, this documentation will only contain examples of two of these helpers.

Example #17 Flash helper

Embedding Flash in your page using the helper is pretty straight-forward. The only required argument is the resource URI.

htmlFlash('/path/to/flash.swf'); ?>

This outputs the following HTML:


Additionally you can specify attributes, parameters and content that can be rendered along with the <object>. This will be demonstrated using the htmlObject helper.

Example #18 Customizing the object by passing additional arguments

The first argument in the object helpers is always required. It is the URI to the resource you want to embed. The second argument is only required in the htmlObject helper. The other helpers already contain the correct value for this argument. The third argument is used for passing along attributes to the object element. It only accepts an array with key-value pairs. The classid and codebase are examples of such attributes. The fourth argument also only takes a key-value array and uses them to create <param> elements. You will see an example of this shortly. Lastly, there is the option of providing additional content to the object. Now for an example which utilizes all arguments.

echo $this->htmlObject(
    '/path/to/file.ext',
    'mime/type',
    array(
        'attr1' => 'aval1',
        'attr2' => 'aval2'
    ),
    array(
        'param1' => 'pval1',
        'param2' => 'pval2'
    ),
    'some content'
);

/*
This would output:


    
    
    some content

*/

InlineScript Helper

The HTML <script> element is used to either provide inline client-side scripting elements or link to a remote resource containing client-side scripting code. The InlineScript helper allows you to manage both. It is derived from HeadScript, and any method of that helper is available; however, use the inlineScript() method in place of headScript().

Note: Use InlineScript for HTML Body Scripts

InlineScript, should be used when you wish to include scripts inline in the HTML body. Placing scripts at the end of your document is a good practice for speeding up delivery of your page, particularly when using 3rd party analytics scripts.

Some JS libraries need to be included in the HTML head; use HeadScript for those scripts.

JSON Helper

When creating views that return JSON, it's important to also set the appropriate response header. The JSON view helper does exactly that. In addition, by default, it disables layouts (if currently enabled), as layouts generally aren't used with JSON responses.

The JSON helper sets the following header:

Content-Type: application/json

Most AJAX libraries look for this header when parsing responses to determine how to handle the content.

Usage of the JSON helper is very straightforward:

json($this->data) ?>

Translate Helper

Often web sites are available in several languages. To translate the content of a site you should simply use Zend Translate and to integrate Zend Translate within your view you should use the Translate View Helper.

In all following examples we are using the simple Array Translation Adapter. Of course you can also use any instance of Zend_Translate and also any subclasses of Zend_Translate_Adapter. There are several ways to initiate the Translate View Helper:

  • Registered, through a previously registered instance in Zend_Registry

  • Afterwards, through the fluent interface

  • Directly, through initiating the class

A registered instance of Zend_Translate is the preferred usage for this helper. You can also select the locale to be used simply before you add the adapter to the registry.

Note:

We are speaking of locales instead of languages because a language also may contain a region. For example English is spoken in different dialects. There may be a translation for British and one for American English. Therefore, we say "locale" instead of "language."

Example #19 Registered instance

To use a registered instance just create an instance of Zend_Translate or Zend_Translate_Adapter and register it within Zend_Registry using Zend_Translate as its key.

// our example adapter
$adapter = new Zend_Translate('array', array('simple' => 'einfach'), 'de');
Zend_Registry::set('Zend_Translate', $adapter);

// within your view
echo $this->translate('simple');
// this returns 'einfach'

If you are more familiar with the fluent interface, then you can also create an instance within your view and initiate the helper afterwards.

Example #20 Within the view

To use the fluent interface, create an instance of Zend_Translate or Zend_Translate_Adapter, call the helper without a parameter, and call the setTranslator() method.

// within your view
$adapter = new Zend_Translate('array', array('simple' => 'einfach'), 'de');
$this->translate()->setTranslator($adapter)->translate('simple');
// this returns 'einfach'

If you are using the helper without Zend_View then you can also use it directly.

Example #21 Direct usage

// our example adapter
$adapter = new Zend_Translate('array', array('simple' => 'einfach'), 'de');

// initiate the adapter
$translate = new Zend_View_Helper_Translate($adapter);
print $translate->translate('simple'); // this returns 'einfach'

You would use this way if you are not working with Zend_View and need to create translated output.

As already seen, the translate() method is used to return the translation. Just call it with the needed messageid of your translation adapter. But it can also replace parameters within the translation string. Therefore, it accepts variable parameters in two ways: either as a list of parameters, or as an array of parameters. As examples:

Example #22 Single parameter

To use a single parameter just add it to the method.

// within your view
$date = "Monday";
$this->translate("Today is %1\$s", $date);
// could return 'Heute ist Monday'

Note:

Keep in mind that if you are using parameters which are also text, you may also need to translate these parameters.

Example #23 List of parameters

Or use a list of parameters and add it to the method.

// within your view
$date = "Monday";
$month = "April";
$time = "11:20:55";
$this->translate("Today is %1\$s in %2\$s. Actual time: %3\$s",
                 $date,
                 $month,
                 $time);
// Could return 'Heute ist Monday in April. Aktuelle Zeit: 11:20:55'

Example #24 Array of parameters

Or use an array of parameters and add it to the method.

// within your view
$date = array("Monday", "April", "11:20:55");
$this->translate("Today is %1\$s in %2\$s. Actual time: %3\$s", $date);
// Could return 'Heute ist Monday in April. Aktuelle Zeit: 11:20:55'

Sometimes it is necessary to change the locale of the translation. This can be done either dynamically per translation or statically for all following translations. And you can use it with both a parameter list and an array of parameters. In both cases the locale must be given as the last single parameter.

Example #25 Change locale dynamically

// within your view
$date = array("Monday", "April", "11:20:55");
$this->translate("Today is %1\$s in %2\$s. Actual time: %3\$s", $date, 'it');

This example returns the Italian translation for the messageid. But it will only be used once. The next translation will use the locale from the adapter. Normally you will set the desired locale within the translation adapter before you add it to the registry. But you can also set the locale from within the helper:

Example #26 Change locale statically

// within your view
$date = array("Monday", "April", "11:20:55");
$this->translate()->setLocale('it');
$this->translate("Today is %1\$s in %2\$s. Actual time: %3\$s", $date);

The above example sets 'it' as the new default locale which will be used for all further translations.

Of course there is also a getLocale() method to get the currently set locale.

Example #27 Get the currently set locale

// within your view
$date = array("Monday", "April", "11:20:55");

// returns 'de' as set default locale from our above examples
$this->translate()->getLocale();

$this->translate()->setLocale('it');
$this->translate("Today is %1\$s in %2\$s. Actual time: %3\$s", $date);

// returns 'it' as new set default locale
$this->translate()->getLocale();

Helper Paths

As with view scripts, your controller can specify a stack of paths for Zend_View to search for helper classes. By default, Zend_View looks in "Zend/View/Helper/*" for helper classes. You can tell Zend_View to look in other locations using the setHelperPath() and addHelperPath() methods. Additionally, you can indicate a class prefix to use for helpers in the path provided, to allow namespacing your helper classes. By default, if no class prefix is provided, 'Zend_View_Helper_' is assumed.

$view = new Zend_View();

// Set path to /path/to/more/helpers, with prefix 'My_View_Helper'
$view->setHelperPath('/path/to/more/helpers', 'My_View_Helper');

In fact, you can "stack" paths using the addHelperPath() method. As you add paths to the stack, Zend_View will look at the most-recently-added path for the requested helper class. This allows you to add to (or even override) the initial distribution of helpers with your own custom helpers.

$view = new Zend_View();
// Add /path/to/some/helpers with class prefix 'My_View_Helper'
$view->addHelperPath('/path/to/some/helpers', 'My_View_Helper');
// Add /other/path/to/helpers with class prefix 'Your_View_Helper'
$view->addHelperPath('/other/path/to/helpers', 'Your_View_Helper');

// now when you call $this->helperName(), Zend_View will look first for
// "/path/to/some/helpers/HelperName" using class name
// "Your_View_Helper_HelperName", then for
// "/other/path/to/helpers/HelperName.php" using class name
// "My_View_Helper_HelperName", and finally for
// "Zend/View/Helper/HelperName.php" using class name
// "Zend_View_Helper_HelperName".

Writing Custom Helpers

Writing custom helpers is easy; just follow these rules:

  • While not strictly necessary, we recommend either implementing Zend_View_Helper_Interface or extending Zend_View_Helper_Abstract when creating your helpers. Introduced in 1.6.0, these simply define a setView() method; however, in upcoming releases, we plan to implement a strategy pattern that will simplify much of the naming schema detailed below. Building off these now will help you future-proof your code.

  • The class name must, at the very minimum, end with the helper name itself, using MixedCaps. E.g., if you were writing a helper called "specialPurpose", the class name would minimally need to be "SpecialPurpose". You may, and should, give the class name a prefix, and it is recommended that you use 'View_Helper' as part of that prefix: "My_View_Helper_SpecialPurpose". (You will need to pass in the prefix, with or without the trailing underscore, to addHelperPath() or setHelperPath()).

  • The class must have a public method that matches the helper name; this is the method that will be called when your template calls "$this->specialPurpose()". In our "specialPurpose" helper example, the required method declaration would be "public function specialPurpose()".

  • In general, the class should not echo or print or otherwise generate output. Instead, it should return values to be printed or echoed. The returned values should be escaped appropriately.

  • The class must be in a file named after the helper class. Again using our "specialPurpose" helper example, the file has to be named "SpecialPurpose.php".

Place the helper class file somewhere in your helper path stack, and Zend_View will automatically load, instantiate, persist, and execute it for you.

Here is an example of our SpecialPurpose helper code:

class My_View_Helper_SpecialPurpose extends Zend_View_Helper_Abstract
{
    protected $_count = 0;
    public function specialPurpose()
    {
        $this->_count++;
        $output = "I have seen 'The Jerk' {$this->_count} time(s).";
        return htmlspecialchars($output);
    }
}

Then in a view script, you can call the SpecialPurpose helper as many times as you like; it will be instantiated once, and then it persists for the life of that Zend_View instance.

// remember, in a view script, $this refers to the Zend_View instance.
echo $this->specialPurpose();
echo $this->specialPurpose();
echo $this->specialPurpose();

The output would look something like this:

I have seen 'The Jerk' 1 time(s).
I have seen 'The Jerk' 2 time(s).
I have seen 'The Jerk' 3 time(s).

Sometimes you will need access to the calling Zend_View object -- for instance, if you need to use the registered encoding, or want to render another view script as part of your helper. To get access to the view object, your helper class should have a setView($view) method, like the following:

class My_View_Helper_ScriptPath
{
    public $view;

    public function setView(Zend_View_Interface $view)
    {
        $this->view = $view;
    }

    public function scriptPath($script)
    {
        return $this->view->getScriptPath($script);
    }
}

If your helper class has a setView() method, it will be called when the helper class is first instantiated, and passed the current view object. It is up to you to persist the object in your class, as well as determine how it should be accessed.

If you are extending Zend_View_Helper_Abstract, you do not need to define this method, as it is defined for you.

Previous Next
Introduction to Zend Framework
Overview
Installation
Zend_Acl
Introduction
Refining Access Controls
Advanced Usage
Zend_Amf
Introduction
Zend_Amf_Server
Zend_Auth
Introduction
Database Table Authentication
Digest Authentication
HTTP Authentication Adapter
LDAP Authentication
Open ID Authentication
Zend_Cache
Introduction
The theory of caching
Zend_Cache frontends
Zend_Cache backends
Zend_Captcha
Introduction
Captcha Operation
Captcha Adapters
Zend_Config
Introduction
Theory of Operation
Zend_Config_Ini
Zend_Config_Xml
Zend_Config_Writer
Zend_Config_Writer
Zend_Console_Getopt
Introduction to Getopt
Declaring Getopt Rules
Fetching Options and Arguments
Configuring Zend_Console_Getopt
Zend_Controller
Zend_Controller Quick Start
Zend_Controller Basics
The Front Controller
The Request Object
The Standard Router
The Dispatcher
Action Controllers
Action Helpers
The Response Object
Plugins
Using a Conventional Modular Directory Structure
MVC Exceptions
Migrating from Previous Versions
Zend_Currency
Introduction to Zend_Currency
How to work with currencies
Migrating from Previous Versions
Zend_Date
Introduction
Theory of Operation
Basic Methods
Zend_Date API Overview
Creation of dates
Constants for General Date Functions
Working examples
Zend_Db
Zend_Db_Adapter
Zend_Db_Statement
Zend_Db_Profiler
Zend_Db_Select
Zend_Db_Table
Zend_Db_Table_Row
Zend_Db_Table_Rowset
Zend_Db_Table Relationships
Zend_Debug
Dumping Variables
Zend_Dojo
Introduction
Zend_Dojo_Data: dojo.data Envelopes
Dojo View Helpers
Dojo Form Elements and Decorators
Zend_Dom
Introduction
Zend_Dom_Query
Zend_Exception
Using Exceptions
Zend_Feed
Introduction
Importing Feeds
Retrieving Feeds from Web Pages
Consuming an RSS Feed
Consuming an Atom Feed
Consuming a Single Atom Entry
Modifying Feed and Entry structures
Custom Feed and Entry Classes
Zend_File
Zend_File_Transfer
Validators for Zend_File_Transfer
Filters for Zend_File_Transfer
Migrating from previous versions
Zend_Filter
Introduction
Standard Filter Classes
Filter Chains
Writing Filters
Zend_Filter_Input
Zend_Filter_Inflector
Zend_Form
Zend_Form
Zend_Form Quick Start
Creating Form Elements Using Zend_Form_Element
Creating Forms Using Zend_Form
Creating Custom Form Markup Using Zend_Form_Decorator
Standard Form Elements Shipped With Zend Framework
Standard Form Decorators Shipped With Zend Framework
Internationalization of Zend_Form
Advanced Zend_Form Usage
Zend_Gdata
Introduction to Gdata
Authenticating with AuthSub
Using the Book Search Data API
Authenticating with ClientLogin
Using Google Calendar
Using Google Documents List Data API
Using Google Health
Using Google Spreadsheets
Using Google Apps Provisioning
Using Google Base
Using Picasa Web Albums
Using the YouTube Data API
Catching Gdata Exceptions
Zend_Http
Zend_Http_Client - Introduction
Zend_Http_Client - Advanced Usage
Zend_Http_Client - Connection Adapters
Zend_Http_Cookie and Zend_Http_CookieJar
Zend_Http_Response
Zend_InfoCard
Introduction
Zend_Json
Introduction
Basic Usage
JSON Objects
XML to JSON conversion
Zend_Json_Server - JSON-RPC server
Zend_Layout
Introduction
Zend_Layout Quick Start
Zend_Layout Configuration Options
Zend_Layout Advanced Usage
Zend_Ldap
Introduction
Zend_Loader
Loading Files and Classes Dynamically
Loading Plugins
Zend_Locale
Introduction
Using Zend_Locale
Normalization and Localization
Working with Dates and Times
Supported locales
Migrating from previous versions
Zend_Log
Overview
Writers
Formatters
Filters
Zend_Mail
Introduction
Sending via SMTP
Sending Multiple Mails per SMTP Connection
Using Different Transports
HTML E-Mail
Attachments
Adding Recipients
Controlling the MIME Boundary
Additional Headers
Character Sets
Encoding
SMTP Authentication
Securing SMTP Transport
Reading Mail Messages
Zend_Measure
Introduction
Creation of Measurements
Outputting measurements
Manipulating Measurements
Types of measurements
Zend_Memory
Overview
Memory Manager
Memory Objects
Zend_Mime
Zend_Mime
Zend_Mime_Message
Zend_Mime_Part
Zend_OpenId
Introduction
Zend_OpenId_Consumer Basics
Zend_OpenId_Provider
Zend_Paginator
Introduction
Usage
Configuration
Advanced usage
Zend_Pdf
Introduction.
Creating and loading PDF documents.
Save changes to the PDF document.
Document pages.
Drawing
Document Info and Metadata.
Zend_Pdf module usage example
Zend_ProgressBar
Zend_ProgressBar
Zend_Registry
Using the Registry
Zend_Rest
Introduction
Zend_Rest_Client
Zend_Rest_Server
Zend_Search_Lucene
Overview
Building Indexes
Searching an Index
Query Language
Query Construction API
Character Set
Extensibility
Interoperating with Java Lucene
Advanced
Best Practices
Zend_Server
Introduction
Zend_Server_Reflection
Zend_Service
Introduction
Zend_Service_Akismet
Zend_Service_Amazon
Zend_Service_Audioscrobbler
Zend_Service_Delicious
Zend_Service_Flickr
Zend_Service_Nirvanix
Zend_Service_ReCaptcha
Zend_Service_Simpy
Introduction
Zend_Service_StrikeIron
Zend_Service_StrikeIron: Bundled Services
Zend_Service_StrikeIron: Advanced Uses
Zend_Service_Technorati
Zend_Service_Twitter
Zend_Service_Yahoo
Zend_Session
Introduction
Basic Usage
Advanced Usage
Global Session Management
Zend_Session_SaveHandler_DbTable
Zend_Soap
Zend_Soap_Server
Zend_Soap_Client
WSDL Accessor
AutoDiscovery
Zend_Test
Introduction
Zend_Test_PHPUnit
Zend_Text
Zend_Text_Figlet
Zend_Text_Table
Zend_TimeSync
Introduction
Working with Zend_TimeSync
Zend_Translate
Introduction
Adapters for Zend_Translate
Using Translation Adapters
Migrating from previous versions
Zend_Uri
Zend_Uri
Zend_Validate
Introduction
Standard Validation Classes
Validator Chains
Writing Validators
Zend_Version
Reading the Zend Framework Version
Zend_View
Introduction
Controller Scripts
View Scripts
View Helpers
Zend_View_Abstract
Zend_Wildfire
Zend_Wildfire
Zend_XmlRpc
Introduction
Zend_XmlRpc_Client
Zend_XmlRpc_Server
Zend Framework Requirements
PHP Version
PHP Extensions
Zend Framework Components
Zend Framework Dependencies
Zend Framework Coding Standard for PHP
Overview
PHP File Formatting
Naming Conventions
Coding Style
Zend Framework Performance Guide
Introduction
Class Loading
Internationalization (i18n) and Localization (l10n)
View Rendering
Copyright Information