Reputation: 13
I'm finding that the Zend "required" validator is generating tips in my forms earlier than I want it to. When a form is first rendered in the browser, before the user has submitted anything, it displays "value is required and can't be empty." I'd like that to only show up after something is submitted that fails the validation check. Is there a Zend-standard way to do this, or do I need to write something that will make this stateful the way I want it?
I'm new so I think this is pretty basic stuff:
Here's the form:
class Application_Form_Login extends Zend_Form
{
public function init()
{
/* Form Elements & Other Definitions Here ... */
$this->setMethod('post');
$this->addElement(
'text', 'username', array(
'label' => 'Username:',
'required' => true,
'filters' => array('StringTrim'),
)
);
$this->addElement('submit', 'submit', array(
'ignore' => true,
'label' => 'Login',
));
}
}
And it's displayed with this code:
public function indexAction()
{
// action body
$db = $this->_getParam('db');
$loginForm = new Application_Form_Login();
if($loginForm->isValid($_POST)) {
$adapter = new Zend_Auth_Adapter_DbTable(
$db,
'users',
'username',
'password',
);
$adapter->setIdentity($loginForm->getValue('username'));
$adapter->setCredential($loginForm->getValue('password'));
$auth = Zend_Auth::getInstance();
$result = $auth->authenticate($adapter);
if ($result->isValid()) {
$this->_helper->FlashMessenger('Successful Login');
$this->redirect('/');
return;
} else {
$this->_helper->FlashMessenger('Unsuccessful Login');
}
}
$this->view->loginForm = $loginForm;
}
Upvotes: 1
Views: 92
Reputation: 2673
You are calling isValid()
before displaying the form the first time, this is why you're getting the error. Probably the $_POST
array is empty.
Try validating only for POST requests, i.e.:
if ($this->getRequest()->isPost()) {
if($loginForm->isValid($_POST)) {
...
}
}
Hope that helps.
Upvotes: 3