views:

25

answers:

1

Hi

Where is it best to put the code for building my Zend_Forms?

I used to put this logic inside my Controllers, but moved away from that after I needed to use the same form in different places. It meant I had to duplicate the creation of forms in different controllers.

So I moved the form creation code into my Models. Does this seem right, it works for me. Or is there something I am missing, and they should in fact go somewhere else?

+4  A: 

I usually put my form building code in separate files, one file per form.
Additionally I configure the Resource Autoloader so that I can load my forms in my controllers.

application/forms/Login.php

<?php
class Form_Login extends Zend_Form
{
    public function init()
    {
        $this->addElement('text', 'username', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'required'   => true,
            'label'      => 'Username:',
        ));

        $this->addElement('password', 'password', array(
            'filters'    => array('StringTrim'),
            'required'   => true,
            'label'      => 'Password:',
        ));

        $this->addElement('submit', 'login', array(
            'ignore'   => true,
            'label'    => 'Submit',
        ));
    }
}

In my controllers:

$loginForm = new Form_Login();
Benjamin Cremer
+1 I'd add also `$model->getForm();` where in model `public function getForm() {return new Form_Login;}`, so the form is always sticky to the model.
takeshin