I’m not really a big fan of Zend_Form, too verbose and less flexible. I’ve been using this little base class for several of my freelance projects. It basically allows you to define validation rules for your model’s columns. This is a very basic version that I’m planning to enhance soon with custom validation functions.
USAGE EXAMPLE
Model
<?
class User extends AbstractModelValidator {
protected $_name = 'users';
protected $_primary = 'id';
protected $_rules = array(
array('name'=>'firstname', 'class'=>'NotEmpty', 'message'=>'Required Field (Firstname)'),
array('name'=>'firstname', 'class'=>'StringLength', 'options'=>array(0, 50),'message'=>'Max length is 50 (Firstname)'),
array('name'=>'lastname', 'class'=>'NotEmpty', 'message'=>'Required Field (Lastname)'),
array('name'=>'lastname', 'class'=>'StringLength', 'options'=>array(0, 50),'message'=>'Max length is 50 (Lastname)'),
);
}
Controller
<?
class UsersController extends Zend_Controller_Action {
public function addAction() {
$this->view->req = $this->_request;
if($this->_request->isPost()) {
$u = new User();
if($u->isValid($this->_request->getParams())) {
}
else {
$this->view->errors = $u->getValidationMessages();
}
}
}
}
View
<html>
<head>
<title>Add User</title>
</head>
<body>
<? if(isset($this->errors) && sizeof($this->errors) > 0): ?>
<ul>
<? foreach($this->errors as $e): ?>
<li><?=$e?></li>
<? endforeach; ?>
</ul>
<? endif; ?>
<div>
<form action="<?=$this->url()?>" method="post">
<div>Firstname:</div>
<div><?=$this->formText('firstname', $this->req->getParam('firstname'), array('size'=>20))?></div>
<div>Lastname::</div>
<div><?=$this->formText('lastname', $this->req->getParam('lastname'), array('size'=>20))?></div>
<div><?=$this->formSubmit('submit', 'Submit')?></div>
</form>
</div>
</body>
</html>