- Content-Type: application/json
Caution: The documentation you are viewing is
for an older version of Zend Framework.
You can find the documentation of the current version at:
View Helpers - Zend_View
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().
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:
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.
The resulting output from the view script will look something like this:
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:
While most URLs generated by the framework have the base URL prepended automatically, developers will need to prepend the base URL to their own URLs in order for paths to resources to be correct.
Usage of the BaseUrl helper is very straightforward:
Note: For simplicity's sake, we strip out the entry PHP file (e.g., "index.php") from the base URL that was contained in Zend_Controller. However, in some situations this may cause a problem. If one occurs, use $this->getHelper('BaseUrl')->setBaseUrl() to set your own BaseUrl.
Displaying localized currency values is a common task; the Zend_Currency view helper is intended to simply this task. See the Zend_Currency documentation for specifics on this localization feature. In this section, we will focus simply on usage of the view helper.
There are several ways to initiate the Currency view helper:
Registered, through a previously registered instance in Zend_Registry.
Afterwards, through the fluent interface.
Directly, through instantiating the class.
A registered instance of Zend_Currency is the preferred usage for this helper. Doing so, you can select the currency to be used prior to adding the adapter to the registry.
There are several ways to select the desired currency. First, you may simply provide a currency string; alternately, you may specify a locale. The preferred way is to use a locale as this information is automatically detected and selected via the HTTP client headers provided when a user accesses your application, and ensures the currency provided will match their locale.
Note: We are speaking of "locales" instead of "languages" because a language may vary based on the geographical region in which it is used. For example, English is spoken in different dialects: British English, American English, etc. As a currency always correlates to a country you must give a fully-qualified locale, which means providing both the language and region. Therefore, we say "locale" instead of "language."
Example #2 Registered instance
To use a registered instance, simply create an instance of Zend_Currency and register it within Zend_Registry using Zend_Currency as its key.
If you are more familiar with the fluent interface, then you can also create an instance within your view and configure the helper afterwards.
Example #3 Within the view
To use the fluent interface, create an instance of Zend_Currency, call the helper without a parameter, and call the setCurrency() method.
If you are using the helper without Zend_View then you can also use it directly.
Example #4 Direct usage
As already seen, the currency() method is used to return the currency string. Just call it with the value you want to display as a currency. It also accepts some options which may be used to change the behaviour and output of the helper.
Example #5 Direct usage
For details about the available options, search for Zend_Currency's toCurrency() method.
The Cycle helper is used to alternate a set of values.
Example #6 Cycle Helper Basic Usage
To add elements to cycle just specify them in constructor or use assign(array $data) function
Example #7 Working with two or more cycles
To use two cycles you have to specify the names of cycles. Just set second parameter in cycle method. $this->cycle(array("#F0F0F0","#FFFFFF"),'cycle2'). You can also use setName($name) function.
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 #8 Basic Usage of Partials
Basic usage of partials is to render a template fragment in its own view scope. Consider the following partial script:
You would then call it from your view script using the following:
Which would then render:
Note: What is a model?
A model used with the Partial view helper can be one of the following:
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:
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.
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).
- // Tell partial to pass objects as 'model' variable
- // Tell partial to pass objects from partialLoop as 'model' variable
- // in final partial view script:
Example #9 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:
And the following "model":
In your view script, you could then invoke the PartialLoop helper:
Example #10 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:
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 #11 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.
Example #12 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.
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.
Example #13 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.
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:
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 #14 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:
And then print it out on top of your layout script:
Example #15 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.
Typically, you'll simply want to know if the doctype is XHTML or not; for this, the isXhtml() method will suffice:
You can also check if the doctype represents an HTML5 document
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 #17 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:
If you wished to set some client-side caching rules, you'd set http-equiv tags with the rules you wish to enforce:
Another popular use for meta tags is setting the content type, character set, and language:
If you are serving an HTML5 document, you should provide the character set like this:
As a final example, an easy way to display a transitional message before a redirect is using a "meta refresh":
When you're ready to place your meta tags in the layout, simply echo the 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:
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 it from specific browsers. To add the conditional tags, pass the conditional value as part of the $attrs parameter in the method calls.
Example #18 Headscript With Conditional Comments
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
Example #19 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.
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:
When you're finally ready to output all scripts in your layout script, simply echo the helper:
Example #20 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:
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().
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.
Note: Use HeadLink to link CSS files
HeadLink should be used to create <link> elements for including external stylesheets. HeadStyle 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 it from specific browsers. To add the conditional tags, pass the conditional value as part of the $attributes parameter in the method calls.
Example #21 Headstyle With Conditional Comments
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.
Note: UTF-8 encoding used by default
By default, Zend Framework uses UTF-8 as its default encoding, and, specific to this case, Zend_View does as well. Character encoding can be set differently on the view object itself using the setEncoding() method (or the the encoding instantiation parameter). However, since Zend_View_Interface does not define accessors for encoding, it's possible that if you are using a custom view implementation with this view helper, you will not have a getEncoding() method, which is what the view helper uses internally for determining the character set in which to encode.
If you do not want to utilize UTF-8 in such a situation, you will need to implement a getEncoding() method in your custom view implementation.
Example #22 HeadStyle Helper Basic Usage
You may specify a new style tag at any time:
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:
When you're finally ready to output all style declarations in your layout script, simply echo the helper:
Example #23 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:
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 = null); by default, the value is appended to the stack (aggregating title segments) if left at null, but you may also specify either 'PREPEND' (place at top of stack) or 'SET' (overwrite stack).
Since setting the aggregating (attach) order on each call to headTitle can be cumbersome, you can set a default attach order by calling setDefaultAttachOrder() which is applied to all headTitle() calls unless you explicitly pass a different attach order as the second parameter.
Example #24 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.
When you're finally ready to render the title in your layout script, simply echo the helper:
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:
htmlFlash() Generates markup for embedding Flash files.
htmlObject() Generates markup for embedding a custom Object.
htmlPage() Generates markup for embedding other (X)HTML pages.
htmlQuicktime() 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 #25 Flash helper
Embedding Flash in your page using the helper is pretty straight-forward. The only required argument is the resource URI.
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 #26 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. 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.
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.
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:
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:
Note: Keeping layouts and enabling encoding using Zend_Json_Expr
Each method in the JSON helper accepts a second, optional argument. This second argument can be a boolean flag to enable or disable layouts, or an array of options that will be passed to Zend_Json::encode() and used internally to encode data.
To keep layouts, the second parameter needs to be boolean TRUE. When the second parameter is an array, keeping layouts can be achieved by including a keepLayouts key with a value of a boolean TRUE.
Zend_Json::encode allows the encoding of native JSON expressions using Zend_Json_Expr objects. This option is disabled by default. To enable this option, pass a boolean TRUE to the enableJsonExprFinder key of the options array:
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 #46 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.
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 #47 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.
If you are using the helper without Zend_View then you can also use it directly.
Example #48 Direct usage
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 #49 Single parameter
To use a single parameter just add it to the method.
Note: Keep in mind that if you are using parameters which are also text, you may also need to translate these parameters.
Example #50 List of parameters
Or use a list of parameters and add it to the method.
Example #51 Array of parameters
Or use an array of parameters and add it to the method.
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 #52 Change locale dynamically
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 Change locale statically
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 #54 Get the currently set locale
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.
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.
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:
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.
The output would look something like this:
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:
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.
Sometimes it is convenient to instantiate a view helper, and then register it with the view. As of version 1.10.0, this is now possible using the registerHelper() method, which expects two arguments: the helper object, and the name by which it will be registered.
If the helper has a setView() method, the view object will call this and inject itself into the helper on registration.
Note: Helper name should match a method
The second argument to registerHelper() is the name of the helper. A corresponding method name should exist in the helper; otherwise, Zend_View will call a non-existent method when invoking the helper, raising a fatal PHP error.