2008年8月31日星期日

Re: [fw-mvc] Passing Zend Form instances around in a controller for validation

-- GJ Bogaerts <gj@zigg.nl> wrote
(on Sunday, 31 August 2008, 09:25 AM -0700):
> I wonder what is the best way to pass an instance of a Zend_Form around in a
> controller. I used to post to the same page as the form was on, so
> validation would be easy: I would instantiate a form, and depending on the
> fact if a post was done, I could validate on the form and forward to another
> page, or present the error messages.
>
> But I want to do post-processing and validation in another action (the same
> controller) and I don't have access to the instantiated form in this other
> action. I've tried to set the form as a protected property of the
> controller, but that doesn't work.
>
> Any ideas or help would be greatly appreciated.
>
> BTW, in the docs I could only find examples of same-page-posts.

I typically add a "getForm()" method to my controller to instantiate and
return the form:

protected $_form;

public function getForm()
{
if (null === $this->_form) {
$this->_form = new My_Form_SomeFunctionalityINeedAFormFor();
$this->_form->setAction(...)
->setMethod('post');
}
return $this->_form;
}

Then, in my actions, I retrieve it:

public function formAction()
{
$this->view->form = $this->getForm();
}

public function processAction()
{
$request = $this->getRequest();
if (!$request->isPost()) {
return $this->_forward('form');
}

$form = $this->getForm();
if (!$form->isValid($request->getPost())) {
return $this->render('form');
}

// process and redirect ...
}

--
Matthew Weier O'Phinney
Software Architect | matthew@zend.com
Zend Framework | http://framework.zend.com/

没有评论: