A Zend Framwork compound form element for dates

Rob Allen writes; A while ago I needed to ask a user for their date of birth on a Zend_Form. The design showed three sep­a­rate select ele­ments to do this:

Screen shot of a 3 select boxes for a date on a form

A lit­tle bit of googling found this site http://codecaine.co.za/posts/compound-elements-with-zend-form which has not unfor­tu­nately dis­ap­peared, so the code in this arti­cle owes a lot of the author of that article.

It turns out to be remark­ably sim­ple to cre­ate a sin­gle Zend Form ele­ment that is ren­dered as mul­ti­ple form ele­ments. We cre­ate an ele­ment object and a view helper object and we’re done. Usage then looks like:


class Application_Form_Details extends Zend_Form
    public function init()
        $this->addPrefixPath('App_Form', 'App/Form/');

        // other elements before
        $this->addElement('date', 'date_of_birth', array(
            'label' => 'Date of birth:'
        // other elements after

        $this->addElement('submit', 'Go');

Obvi­ously, this form lives in application/forms/Detail.php and is ren­dered as usual in a view script. In our form def­i­n­i­tion, we have added an ele­ment called ‘date’ and with the addi­tion of the addPre­fix­Path call have told the form that in addi­tion to using the stan­dard Zend Frame­work form ele­ments, also look in library/App/Form. (Inci­den­tally, we can also now over­ride any sup­plied form ele­ment by sim­ply drop­ping a replace­ment into the libraryApp/Form folder.)

The date form ele­ment lives in library/App/Form/Element/Date.php as Zend_Form knows to look in a sub­folder for App/Form called Ele­ments for any ele­ment objects and will look in the Decorator/ sub folder for dec­o­ra­tor objects.

The Date ele­ment looks like this:

Read the rest at Rob Allen’s DevNotes.

Tags: ,

Leave a Comment


Get Adobe Flash player