2

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?

Benjamin Cremer
  • 4,842
  • 1
  • 24
  • 30
Jake N
  • 10,535
  • 11
  • 66
  • 112

1 Answers1

5

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
  • 4,842
  • 1
  • 24
  • 30
  • +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 Sep 02 '10 at 17:51
  • "Additionally I configure the Resource Autoloader so that I can load my forms in my controllers". Any chance you could elaborate on this? – voidstate Dec 13 '11 at 10:20
  • voidstate: Maybe this answer may help you: http://stackoverflow.com/questions/6264812/autoloading-in-zend-framework/6265759#6265759 – Benjamin Cremer Dec 13 '11 at 13:49