Rendering Individual Decorators

Creating and Rendering Composite Elements

In the last section, we had an example showing a "date of birth element":

  1. span style="color: #ff0000;">"element"'dateOfBirth[day]', '''size' => 2, 'maxlength''dateOfBirth[month]', '''size' => 2, 'maxlength''dateOfBirth[year]', '''size' => 4, 'maxlength'

How might you represent this element as a Zend_Form_Element? How might you write a decorator to render it?

The Element

The questions about how the element would work include:

  • How would you set and retrieve the value?

  • How would you validate the value?

  • Regardless, how would you then allow for discrete form inputs for the three segments (day, month, year)?

The first two questions center around the form element itself: how would setValue() and getValue() work? There's actually another question implied by the question about the decorator: how would you retrieve the discrete date segments from the element and/or set them?

The solution is to override the setValue() method of your element to provide some custom logic. In this particular case, our element should have three discrete behaviors:

  • If an integer timestamp is provided, it should be used to determine and store the day, month, and year.

  • If a textual string is provided, it should be cast to a timestamp, and then that value used to determine and store the day, month, and year.

  • If an array containing keys for date, month, and year is provided, those values should be stored.

Internally, the day, month, and year will be stored discretely. When the value of the element is retrieved, it will be done so in a normalized string format. We'll override getValue() as well to assemble the discrete date segments into a final string.

Here's what the class would look like:

  1. span style="color: #ff0000;">'%year%-%month%-%day%''d''m''Y''d''m''Y''day''month''year'])
  2.                   )
  3.         ) {
  4.             $this->setDay($value['day'])
  5.                  ->setMonth($value['month'])
  6.                  ->setYear($value['year''Invalid date value provided''%year%', '%month%', '%day%'

This class gives some nice flexibility -- we can set default values from our database, and be certain that the value will be stored and represented correctly. Additionally, we can allow for the value to be set from an array passed via form input. Finally, we have discrete accessors for each date segment, which we can now use in a decorator to create a composite element.

The Decorator

Revisiting the example from the last section, let's assume that we want users to input each of the year, month, and day separately. PHP fortunately allows us to use array notation when creating elements, so it's still possible to capture these three entities into a single value -- and we've now created a Zend_Form element that can handle such an array value.

The decorator is relatively simple: it will grab the day, month, and year from the element, and pass each to a discrete view helper to render individual form inputs; these will then be aggregated to form the final markup.

  1. span style="color: #808080; font-style: italic;">// only want to render Date elements
  2. // using view helpers, so do nothing if no view present
  3. 'size'      => 2,
  4.             'maxlength''size'      => 4,
  5.             'maxlength''[day]', $day, $params)
  6.                 . ' / ''[month]', $month, $params)
  7.                 . ' / ''[year]'

We now have to do a minor tweak to our form element, and tell it that we want to use the above decorator as a default. That takes two steps. First, we need to inform the element of the decorator path. We can do that in the constructor:

  1. span style="color: #808080; font-style: italic;">// ...
  2. 'My_Form_Decorator',
  3.             'My/Form/Decorator',
  4.             'decorator'// ...
  5. }

Note that this is being done in the constructor and not in init(). This is for two reasons. First, it allows extending the element later to add logic in init without needing to worry about calling parent::init(). Second, it allows passing additional plugin paths via configuration or within an init method that will then allow overriding the default Date decorator with my own replacement.

Next, we need to override the loadDefaultDecorators() method to use our new Date decorator:

  1. span style="color: #808080; font-style: italic;">// ...
  2. 'Date')
  3.                  ->addDecorator('Errors')
  4.                  ->addDecorator('Description''tag'   => 'p',
  5.                      'class' => 'description'
  6.                  ))
  7.                  ->addDecorator('HtmlTag''tag' => 'dd',
  8.                      'id'  => $this->getName() . '-element'
  9.                  ))
  10.                  ->addDecorator('Label''tag' => 'dt'));
  11.         }
  12.     }
  13.  
  14.     // ...
  15. }

What does the final output look like? Let's consider the following element:

  1. span style="color: #ff0000;">'dateOfBirth');
  2. $d->setLabel('Date of Birth: '// These are equivalent:
  3. $d->setValue('20 April 2009''year' => '2009', 'month' => '04', 'day' => '20'));

If you then echo this element, you get the following markup (with some slight whitespace modifications for readability):

  1. <dt id="dateOfBirth-label"><label for="dateOfBirth" class="optional">
  2.     Date of Birth:
  3. </label></dt>
  4. <dd id="dateOfBirth-element">
  5.     <input type="text" name="dateOfBirth[day]" id="dateOfBirth-day"
  6.         value="20" size="2" maxlength="2"> /
  7.     <input type="text" name="dateOfBirth[month]" id="dateOfBirth-month"
  8.         value="4" size="2" maxlength="2"> /
  9.     <input type="text" name="dateOfBirth[year]" id="dateOfBirth-year"
  10.         value="2009" size="4" maxlength="4">
  11. </dd>

Conclusion

We now have an element that can render multiple related form input fields, and then handle the aggregated fields as a single entity -- the dateOfBirth element will be passed as an array to the element, and the element will then, as we noted earlier, create the appropriate date segments and return a value we can use for most backends.

Additionally, we can use different decorators with the element. If we wanted to use a » Dojo DateTextBox dijit decorator -- which accepts and returns string values -- we can, with no modifications to the element itself.

In the end, you get a uniform element API you can use to describe an element representing a composite value.


Rendering Individual Decorators