Question

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

Was it helpful?

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.

OTHER TIPS

If a form appears in, say, the sidebar of a layout - like a "Subscribe to our mailing list" form - it seems reasonable to allow the view to create/render it on its own, though I'd probably do it within a view helper rather than have any new My_Form() calls in a view script. Why force every controller to deal with it?

As Padraic Brady notes in his online ZF book Surviving the Deep End: "Controllers Are Not The Data Police".

I think the only first variant is correct, because Zend_Form is not presentation entity, but business logic entity. So it's wrong to try to instantiate it in the view. If you want simply display some form just mark up it directly in HTML - this will be much more easier for coder at least.

Think about your team mates, are your designers( or graphical integrators ) programmers too? that approach will break down re-usability, and tasks separation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top