Zend_Validate:Db_NoRecordExists with Doctrine

时间:2009-09-08 19:47:47

标签: php zend-framework doctrine

嘿那里,我正在尝试使用Zend_Validate和Zend_Form验证表单。

我的元素:

$this->addElement('text', 'username', array(
    'validators' => array(
        array(
            'validator' => 'Db_NoRecordExists',
            'options' => array('user','username')
            )
    )
));

因为我使用Doctrine处理我的数据库,Zend_Validate错过了一个DbAdapter。我可以在选项中传递适配器,但如何组合Zend_Db_Adapter_Abstract和Doctrine?

是否有更简单的方法可以完成这项工作?

谢谢!

1 个答案:

答案 0 :(得分:9)

使用自己的验证器解决它:

<?php

class Validator_NoRecordExists extends Zend_Validate_Abstract
{
    private $_table;
    private $_field;

    const OK = '';

    protected $_messageTemplates = array(
        self::OK => "'%value%' ist bereits in der Datenbank"
    );

    public function __construct($table, $field) {
        if(is_null(Doctrine::getTable($table)))
            return null;

        if(!Doctrine::getTable($table)->hasColumn($field))
            return null;

        $this->_table = Doctrine::getTable($table);
        $this->_field = $field;
    }

    public function isValid($value)
    {
        $this->_setValue($value);

        $funcName = 'findBy' . $this->_field;

        if(count($this->_table->$funcName($value))>0) {
            $this->_error();
            return false;
        }

        return true;
    }
}

像这样使用:

$this->addElement('text', 'username', array(
    'validators' => array(
        array(
            'validator' => new Validator_NoRecordExists('User','username')
            )
    )
));