Posted by Kamil Adryjanek | Posted on 30-01-2011
Category : PHP, Zend Framework
Tags: PHP, Tutorial, validation, zend framework, Zend_Form
Zend framework has a lot of o really nice features. Lately i had an opportunity to work with Zend_Form (also with its validation system) and Zend_Db (my most hated component of ZF). Playing with DB i needed a simple way to check if new item (record) is unique. Unfortunately i haven’t found Zend_Validate_Db_Unique component
There is Zend_Validate_Db_NoRecordExists/RecordExists but it only checks if record exists/not exists in db. The code below is my proposal for new validation component:
/**
* @see Zend_Validate_Db_Abstract
*/
require_once 'Zend/Validate/Db/Abstract.php';
/**
* Confirms a record is unique in a table.
*
* @uses Zend_Validate_Db_Abstract
*/
class Zend_Validate_Db_Unique extends Zend_Validate_Db_Abstract
{
/**
* @var Zend_DB_Table_Row
*/
protected $_row = null;
public function __construct($table, $field, Zend_DB_Table_Row $row, Zend_Db_Adapter_Abstract $adapter = null)
{
parent::__construct($table, $field, null, $adapter);
$this->_row = $row;
$this->setMessage("A record matching %value% already exists.", self::ERROR_RECORD_FOUND);
}
public function isValid($value)
{
$valid = true;
$this->_setValue($value);
$result = $this->_query($value);
if (!$result || $this->isUpdate()) {
return true;
}
$this->_error(self::ERROR_RECORD_FOUND);
return false;
}
protected function isUpdate()
{
if (!isset($this->_row[$this->_field]) || $this->_row[$this->_field] != $this->_value)
{
return false;
}
return true;
}
}
→ Continue