Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
535 views
in Technique[技术] by (71.8m points)

php - Zend_Validate: Db_NoRecordExists with Doctrine

Hey there, I'm trying to validate a form with Zend_Validate and Zend_Form.

My element:

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

For I use Doctrine to handle my database, Zend_Validate misses a DbAdapter. I could pass an adapter in the options, but how do I combine Zend_Db_Adapter_Abstract and Doctrine?

Is there maybe an easyer way to get this done?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Solved it with an own Validator:

<?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;
    }
}

Used like that:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...