I have a simple Zend Form that contains a textbox with setRequired(TRUE) and other validators and a simple submit button in IndexController.
My question is, is it possible another controller will process and validate my post form?
Login.php
<?php
class Application_Form_Login extends Zend_Form
{
public function init()
{
$username = $this->createElement('text', 'username');
$username->setLabel('Username:');
$username->setRequired(TRUE);
$username->addValidator(new Zend_Validate_StringLength(array('min' => 3, 'max' => 10)));
$username->addFilters(array(
new Zend_Filter_StringTrim(),
new Zend_Filter_StringToLower()
)
);
$this->addElement($username);
// create submit button
$this->addElement('submit', 'login',
array('required' => false,
'ignore' => true,
'label' => 'Login'));
}}
IndexController.php
<?php
class AttendantController extends Zend_Controller_Action
{
public function indexAction()
{
$loginForm = new Application_Form_Login();
$loginForm->setAction('/Auth/process');
$loginForm->setMethod('post');
$this->view->loginForm = $loginForm;
}
}
AuthController.php
class AuthController extends Zend_Controller_Action
{
public function processAction()
{
// How to validate the form posted here in this action function?
// I have this simple code but I'm stacked here validating the form
// Get the request
$request = $this->getRequest();
// Create a login form
$loginForm = new Application_Form_Login();
// Checks the request if it is a POST action
if($request->isPost()) {
$loginForm->populate($request->getPost());
// This is where I don't know how validate the posted form
if($loginForm->isValid($_POST)) {
// codes here
}
}
}
}
You’re pretty close. In the process action you create a new instance of the login form (which you are doing), and you pass the POST data to the
isValid()method of that form in order to validate. So:Generally it is easier to display and process the form within the same action, and redirect when the submission is successful. This is the Post/Redirect/Get pattern – see http://en.wikipedia.org/wiki/Post/Redirect/Get. This saves you having to create an instance of the same form in two different actions and makes it easier to redisplay the form in case of errors.