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()
.
![]() |
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. |
![]() |
Default Helper Path |
---|---|
The default helper path always points to the Zend Framework view
helpers, i.e., 'Zend/View/Helper/'. Even if you call
|
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()
.
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'). ?> <form action="action.php" method="post"> <p><label>Your Email: <?php echo $this->formText('email', 'you@example.com', array('size' => 32)) ?> </label></p> <p><label>Your Country: <?php echo $this->formSelect('country', 'us', null, $this->countries) ?> </label></p> <p><label>Would you like to opt in? <?php echo $this->formCheckbox('opt_in', 'yes', null, array('yes', 'no')) ?> </label></p> </form>
The resulting output from the view script will look something like this:
<form action="action.php" method="post"> <p><label>Your Email: <input type="text" name="email" value="you@example.com" size="32" /> </label></p> <p><label>Your Country: <select name="country"> <option value="us" selected="selected">United States</option> <option value="il">Israel</option> <option value="de">Germany</option> </select> </label></p> <p><label>Would you like to opt in? <input type="hidden" name="opt_in" value="no" /> <input type="checkbox" name="opt_in" value="yes" checked="checked" /> </label></p> </form>
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 53.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:
<div id="sidebar right"> <div class="item"> <?php echo $this->action('list', 'comment', null, array('count' => 10)); ?> </div> </div>
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.
![]() |
PartialLoop Counter |
---|---|
The |
Example 53.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:
<?php // partial.phtml ?> <ul> <li>From: <?php echo $this->escape($this->from) ?></li> <li>Subject: <?php echo $this->escape($this->subject) ?></li> </ul>
You would then call it from your view script using the following:
<?php echo $this->partial('partial.phtml', array( 'from' => 'Team Framework', 'subject' => 'view partials')); ?>
Which would then render:
<ul> <li>From: Team Framework</li> <li>Subject: view partials</li> </ul>
![]() |
What is a model? |
---|---|
A model used with the
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
|
Example 53.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:
<?php // partialLoop.phtml ?> <dt><?php echo $this->key ?></dt> <dd><?php echo $this->value ?></dd>
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:
<dl> <?php echo $this->partialLoop('partialLoop.phtml', $model) ?> </dl>
<dl> <dt>Mammal</dt> <dd>Camel</dd> <dt>Bird</dt> <dd>Penguin</dd> <dt>Reptile</dt> <dd>Asp</dd> <dt>Fish</dt> <dd>Flounder</dd> </dl>
Example 53.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:
<?php echo $this->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.
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 53.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.
<?php $this->placeholder('foo')->set("Some text for later") ?> <?php echo $this->placeholder('foo'); // outputs "Some text for later" ?>
Example 53.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.
<!-- first view script --> <?php $this->placeholder('foo')->exchangeArray($this->data) ?>
<!-- later view script --> <?php $this->placeholder('foo')->setPrefix("<ul>\n <li>") ->setSeparator("</li><li>\n") ->setIndent(4) ->setPostfix("</li></ul>\n"); ?> <?php echo $this->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.
<?php $this->placeholder('foo')->bar = $this->data ?> <?php echo $this->placeholder('foo')->bar ?> <?php $foo = $this->placeholder('foo'); echo $foo['bar']; ?>
Example 53.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.
<!-- Default capture: append --> <?php $this->placeholder('foo')->captureStart(); foreach ($this->data as $datum): ?> <div class="foo"> <h2><?php echo $datum->title ?></h2> <p><?php echo $datum->content ?></p> </div> <?php endforeach; ?> <?php $this->placeholder('foo')->captureEnd() ?> <?php echo $this->placeholder('foo') ?>
<!-- Capture to key --> <?php $this->placeholder('foo')->captureStart('SET', 'data'); foreach ($this->data as $datum): ?> <div class="foo"> <h2><?php echo $datum->title ?></h2> <p><?php echo $datum->content ?></p> </div> <?php endforeach; ?> <?php $this->placeholder('foo')->captureEnd() ?> <?php echo $this->placeholder('foo')->data ?>
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:
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 53.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:
<?php echo $this->doctype() ?>
Example 53.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 }
The HTML <link>
element is increasingly used for
linking a variety of resources for your site: stylesheets, feeds,
favicons, trackbacks, and more. The HeadLink
helper
provides a simple interface for creating and aggregating these elements
for later retrieval and output in your layout script.
The HeadLink
helper has special methods for adding
stylesheet links to its stack:
appendStylesheet($href, $media,
$conditionalStylesheet, $extras)
offsetSetStylesheet($index, $href, $media,
$conditionalStylesheet, $extras)
prependStylesheet($href, $media,
$conditionalStylesheet, $extras)
setStylesheet($href, $media,
$conditionalStylesheet, $extras)
The $media
value defaults to 'screen', but may be any valid
media value. $conditionalStylesheet
is a string or boolean false,
and will be used at rendering time to determine if special comments should be
included to prevent loading of the stylesheet on certain platforms.
$extras
is an array of any extra values that you want to be added
to the tag.
Additionally, the HeadLink
helper has special methods for
adding 'alternate' links to its stack:
appendAlternate($href, $type,
$title, $extras)
offsetSetAlternate($index, $href, $type,
$title, $extras)
prependAlternate($href, $type,
$title, $extras)
setAlternate($href, $type,
$title, $extras)
The headLink()
helper method allows specifying all
attributes necessary for a <link>
element, and allows
you to also specify placement -- whether the new element replaces all
others, prepends (top of stack), or appends (end of stack).
The HeadLink
helper is a concrete implementation of the
Placeholder
helper.
Example 53.10. HeadLink Helper Basic Usage
You may specify a headLink
at any time. Typically, you
will specify global links in your layout script, and application
specific links in your application view scripts. In your layout
script, in the <head> section, you will then echo the helper
to output it.
<?php // setting links in a view script: $this->headLink()->appendStylesheet('/styles/basic.css') ->headLink(array('rel' => 'favicon', 'href' => '/img/favicon.ico'), 'PREPEND') ->prependStylesheet('/styles/moz.css', 'screen', true, array('id' => 'my_stylesheet')); ?> <?php // rendering the links: ?> <?php echo $this->headLink() ?>
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 53.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:
<?php echo $this->headMeta() ?>
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.
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.
![]() |
Use InlineScript for HTML Body Scripts |
---|---|
|
![]() |
Arbitrary Attributes are Disabled by Default |
---|---|
By default, $this->headScript()->setAllowArbitraryAttributes(true); |
Example 53.13. 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:
<?php echo $this->headScript() ?>
Example 53.14. 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:
<?php $this->headScript()->captureStart() ?> var action = '<?php echo $this->baseUrl ?>'; $('foo_form').action = action; <?php $this->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()
.
The HTML <style>
element is used to include
CSS stylesheets inline in the HTML <head>
element.
![]() |
Use HeadLink to link CSS files |
---|---|
HeadLink
should be used to create |
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.
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 53.16. 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:
<?php echo $this->headStyle() ?>
Example 53.17. 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:
<?php $this->headStyle()->captureStart() ?> body { background-color: <?php echo $this->bgColor ?>; } <?php $this->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()
.
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 53.18. 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:
<!-- renders <action> / <controller> / Zend Framework --> <?php echo $this->headTitle() ?>
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 53.19. Flash helper
Embedding Flash in your page using the helper is pretty straight-forward. The only required argument is the resource URI.
<?php echo $this->htmlFlash('/path/to/flash.swf'); ?>
This outputs the following HTML:
<object data="/path/to/flash.swf" type="application/x-shockwave-flash" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab"> </object>
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 53.20. 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: <object data="/path/to/file.ext" type="mime/type" attr1="aval1" attr2="aval2"> <param name="param1" value="pval1" /> <param name="param2" value="pval2" /> some content </object> */
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()
.
![]() |
Use InlineScript for HTML Body Scripts |
---|---|
Some JS libraries need to be included in the HTML |
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:
<?php echo $this->json($this->data) ?>
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 53.21. 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 53.22. 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 53.23. 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 53.24. 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 53.25. 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 53.26. 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 53.27. 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 53.28. 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 53.29. 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();
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 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.