Creating Forms Using Zend_Form | Zend_Form Programmer's Reference Guide | Standard Form Elements Shipped With Zend Framework

# Creating Custom Form Markup Using Zend_Form_Decorator

Rendering a form object is completely optional -- you do not need to use Zend_Form's render() methods at all. However, if you do, decorators are used to render the various form objects.

An arbitrary number of decorators may be attached to each item (elements, display groups, sub forms, or the form object itself); however, only one decorator of a given type may be attached to each item. Decorators are called in the order they are registered. Depending on the decorator, it may replace the content passed to it, or append or prepend the content.

Object state is set via configuration options passed to the constructor or the decorator's setOptions() method. When creating decorators via an item's addDecorator() or related methods, options may be passed as an argument to the method. These can be used to specify placement, a separator to use between passed in content and newly generated content, and whatever options the decorator supports.

Before each decorator's render() method is called, the current item is set in the decorator using setElement(), giving the decorator awareness of the item being rendered. This allows you to create decorators that only render specific portions of the item -- such as the label, the value, error messages, etc. By stringing together several decorators that render specific element segments, you can build complex markup representing the entire item.

# Operation

To configure a decorator, pass an array of options or a Zend_Config object to its constructor, an array to setOptions(), or a Zend_Config object to setConfig().

Standard options include:

- placement: Placement can be either 'append' or 'prepend' (case insensitive), and indicates whether content passed to render() will be appended or prepended, respectively. In the case that a decorator replaces the content, this setting is ignored. The default setting is to append.

- separator: The separator is used between the content passed to render() and new content generated by the decorator, or between items rendered by the decorator (e.g. FormElements uses the separator between each item rendered). In the case that a decorator replaces the content, this setting may be ignored. The default value is `PHP_EOL`.

The decorator interface specifies methods for interacting with options. These include:

- setOption($key, $value): set a single option.

- getOption($key): retrieve a single option value.

- getOptions(): retrieve all options.

- removeOption($key): remove a single option.

- clearOptions(): remove all options.

Decorators are meant to interact with the various Zend_Form class types: Zend_Form, Zend_Form_Element, Zend_Form_DisplayGroup, and all classes deriving from them. The method setElement() allows you to set the object the decorator is currently working with, and getElement() is used to retrieve it.

Each decorator's render() method accepts a string, $content. When the first decorator is called, this string is typically empty, while on subsequent calls it will be populated. Based on the type of decorator and the options passed in, the decorator will either replace this string, prepend the string, or append the string; an optional separator will be used in the latter two situations.

# Standard Decorators

Zend_Form ships with many standard decorators; see the chapter on Standard Decorators for details.

# Custom Decorators

If you find your rendering needs are complex or need heavy customization, you should consider creating a custom decorator.

Decorators need only implement Zend_Form_Decorator_Interface. The interface specifies the following:

1. interface Zend_Form_Decorator_Interface
2. {
3. public function __construct($options = null);
4. public function setElement($element);
5. public function getElement();
6. public function setOptions( array $options);
7. public function setConfig(Zend_Config $config);
8. public function setOption($key, $value);
9. public function getOption($key);
10. public function getOptions();
11. public function removeOption($key);
12. public function clearOptions();
13. public function render($content);
14. }

To make this simpler, you can simply extend Zend_Form_Decorator_Abstract, which implements all methods except render().

As an example, let's say you want to reduce the number of decorators you use, and build a "composite" decorator to take care of rendering the label, element, any error messages, and description in an HTML 'div'. You might build such a 'Composite' decorator as follows:

1. class My_Decorator_Composite extends Zend_Form_Decorator_Abstract
2. {
3. public function buildLabel()
4. {
5. $element = $this->getElement();
6. $label = $element->getLabel();
7. if ($translator = $element->getTranslator()) {
8. $label = $translator->translate($label);
9. }
10. if ($element->isRequired()) {
11. $label .= '*';
12. }
13. $label .= ':';
14. return $element->getView()
15. ->formLabel($element->getName(), $label);
16. }
18. public function buildInput()
19. {
20. $element = $this->getElement();
21. $helper = $element->helper;
22. return $element->getView()->$helper(
23. $element->getName(),
24. $element->getValue(),
25. $element->getAttribs(),
26. $element->options
27. );
28. }
30. public function buildErrors()
31. {
32. $element = $this->getElement();
33. $messages = $element->getMessages();
34. if ( empty ($messages)) {
35. return '';
36. }
37. return '<div class="errors">' .
38. $element->getView()->formErrors($messages) . '</div>';
39. }
41. public function buildDescription()
42. {
43. $element = $this->getElement();
44. $desc = $element->getDescription();
45. if ( empty ($desc)) {
46. return '';
47. }
48. return '<div class="description">' . $desc . '</div>';
49. }
51. public function render($content)
52. {
53. $element = $this->getElement();
54. if (!$element instanceof Zend_Form_Element) {
55. return $content;
56. }
57. if (null === $element->getView()) {
58. return $content;
59. }
61. $separator = $this->getSeparator();
62. $placement = $this->getPlacement();
63. $label = $this->buildLabel();
64. $input = $this->buildInput();
65. $errors = $this->buildErrors();
66. $desc = $this->buildDescription();
68. $output = '<div class="form element">'
69. . $label
70. . $input
71. . $errors
72. . $desc
73. . '</div>'
75. switch ($placement) {
76. case (self::PREPEND):
77. return $output . $separator . $content;
78. case (self::APPEND):
79. default:
80. return $content . $separator . $output;
81. }
82. }
83. }

You can then place this in the decorator path:

1. // for an element:
2. $element->addPrefixPath('My_Decorator',
3. 'My/Decorator/',
4. 'decorator');
6. // for all elements:
7. $form->addElementPrefixPath('My_Decorator',
8. 'My/Decorator/',
9. 'decorator');

You can then specify this decorator as 'Composite' and attach it to an element:

1. // Overwrite existing decorators with this single one:
2. $element->setDecorators( array ('Composite'));

While this example showed how to create a decorator that renders complex output from several element properties, you can also create decorators that handle a single aspect of an element; the 'Decorator' and 'Label' decorators are excellent examples of this practice. Doing so allows you to mix and match decorators to achieve complex output -- and also override single aspects of decoration to customize for your needs.

For example, if you wanted to simply display that an error occurred when validating an element, but not display each of the individual validation error messages, you might create your own 'Errors' decorator:

1. class My_Decorator_Errors
2. {
3. public function render($content = '')
4. {
5. $output = '<div class="errors">The value you provided was invalid;
6. please try again</div>';
8. $placement = $this->getPlacement();
9. $separator = $this->getSeparator();
11. switch ($placement) {
12. case 'PREPEND':
13. return $output . $separator . $content;
14. case 'APPEND':
15. default:
16. return $content . $separator . $output;
17. }
18. }
19. }

In this particular example, because the decorator's final segment, 'Errors', matches the same as Zend_Form_Decorator_Errors, it will be rendered in place of that decorator -- meaning you would not need to change any decorators to modify the output. By naming your decorators after existing standard decorators, you can modify decoration without needing to modify your elements' decorators.

# Rendering Individual Decorators

Since decorators can target distinct metadata of the element or form they decorate, it's often useful to render one individual decorator at a time. This behavior is possible via method overloading in each major form class type (forms, sub form, display group, element).

To do so, simply call render[DecoratorName](), where "[DecoratorName]" is the "short name" of your decorator; optionally, you can pass in content you want decorated. For example:

1. // render just the element label decorator:
2. echo $element->renderLabel();
4. // render just the display group fieldset, with some content:
5. echo $group->renderFieldset('fieldset content');
7. // render just the form HTML tag, with some content:
8. echo $form->renderHtmlTag('wrap this content');

If the decorator does not exist, an exception is raised.

This can be useful particularly when rendering a form with the ViewScript decorator; each element can use its attached decorators to generate content, but with fine-grained control.

Creating Forms Using Zend_Form | Zend_Form Programmer's Reference Guide | Standard Form Elements Shipped With Zend Framework