Search code examples
zend-frameworkzend-formzend-viewzend-controller

Zend_Form:: When should be form created in view and not in controller?


Zend_Form:: When should be form created in view and not in controller?

option 1 - form created in controller and passed to view (usually used)

controller:

$form=new MyForm();
$this->view->form=$form;

view:

echo $this->form;

option 2 - form created in view directly (looks better to me because form its subpart of view)

view:

$form=new MyForm();
echo $this->form;

Thanks


Solution

  • In short: newer in view.

    You may eventually:

    • create view helper for complex tasks (and call the helper in view $this->getForm()),
    • or use Model::getForm()
    • or service::getForm() when you need cross-action forms.

    Further explanation:

    Because in the ideal case, views contain only HTML, to separate logic from presentation (MVC).

    When using TDD, you write tests for logic, never for view scripts, which are only clothes for the variables.

    Displaying the form, is not only the form itself, but also checking whether it was submitted or not, checking for validation errors, setting flash messenger variables and much more.

    These are too complex tasks for putting them to view scripts.

    As a good exercise on separating logic and presentation, I recommend you to take a look at PHPTAL template language, which is a nice alternative to native PHP as a template language used in ZF.