28.4. View Helpers
Prev | Chapter 28. Zend_View | Next

## 28.4. 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.

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().

### 28.4.1. Initial Helpers

Zend_View comes with an initial set of helper classes, all of which relate to form element generation. They each perform the appopriate output escaping automatically. They are:

- formButton($name, $value, $attribs): Creates an <input type="button" /> element.

- formCheckbox($name, $value, $attribs, $options): Creates an <input type="checkbox" /> element. The $options param is an array where the first value is the "checked" value, and the second is the "unchecked" value (the defaults are '1' and '0'). If $value matches the "checked" value, the box will be checked for you.

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

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

- 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.

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.

    <?php
    // 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>

### 28.4.2. 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.

    <?php
    $view = new Zend_View();

    // Set path to /path/to/more/helpers, with previs '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.

    <?php
    $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
    // "/other/path/to/helpers/HelperName.php" using class name "My_View_Helper_HelperName",
    // then for "/path/to/some/helpers/HelperName" using class name "Your_View_Helper_HelperName",
    // and finally for "Zend/View/Helper/HelperName.php" using class name "Zend_View_Helper_HelperName".
    ?>

### 28.4.3. Writing Custom Helpers

Writing custom helpers is easy; just follow these rules:

- The class name must, at the very minimum, end with the helper name itself, using CamelCaps. 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 file named after the helper method. 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:

    <?php
    class My_View_Helper_SpecialPurpose {
        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.

    <?php
    // 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).

Prev | Up | Next
28.3. View Scripts | Home | Chapter 29. Zend_XmlRpc