I have an issue with redisplaying a view after a validation failure with a Zend form.
My initial action looks like
public function test1Action() {
// get a form and pass it to the view
$this->view->form = $this->getForm();
// extra stuff I need to display
$this->view->name = "Bob";
}
and the view
Hello <?= $this->name?>
<?php echo $this->form;?>
The problem comes when the action “test2” called after the form is submitted has a validation error :
public function test2Action() {
if (!$this->getRequest()->isPost()) {
return $this->_forward('test1');
}
$form = $this->getForm();
if (!$form->isValid($_POST)) {
$this->view->form = $form;
return $this->render('test1'); // go back to test1
}
}
Indeed, the variable “name” is lost and the view is incorrect. Instead of saying “Hello Bob” it says “Hello”.
How should I handle that ? should I redirect to test1 instead of just rendering test1 again ? how ?
EDIT
Following the answer of Mr Coder, here is what I ended up with :
Controller:
public function getForm() {
// what is important is that the form goes to action test3 and not test4
// SNIP form creation with a field username
return $form;
}
public function test3Action()
{
$this->view->form = $this->getForm();
$this->view->name = "Bob";
if(!$this->getRequest()->isPost())return;
if($this->view->form->isValid($_POST))
{
//save the data and redirect
$values = $this->view->form->getValues();
$username = $values["username"];
$defaultSession = new Zend_Session_Namespace('asdf');
$defaultSession->username = $username;
$this->_helper->redirector('test4');
}
}
public function test4Action()
{
$defaultSession = new Zend_Session_Namespace('asdf');
$this->view->username = $defaultSession->username;
}
test3.phtml
Hello <?= $this->name?>
<?php echo $this->form;?>
test4.phtml
success for <?php echo $this->username;?>
To bring your bob back do
But I will advice my solution of handling form which goes something like
inside your test2.phtml
}
This approach save you from creating multiple action for saving one form and changing view manually.