by Kevin Schroeder | 12:00 am

Doing some work on a little project of mine while waiting for the keynote to start. What I'm doing is writing a form that needs to make sure that a record is unique in the DB.  Doing that in ZF is really easy.  Simple set your validator as Db_NoRecordExists.  What this does is during the Zend_Form::isValid() functionality it will query the database as part of the validation process.  The only parameters you really need are the table and the field if you have already set a default adapter for your Zend_Db models.  That makes it really easy to use.  Here's a slice of how I did it.


class Form_Tweepeater extends Zend_Form
{
    public function init()
    {
        $this->addElement(
            'text',
            'hash',
            array(
                'label'    => 'Hashtag to watch for (no #)',
                'filters'    => array(
                    array('PregReplace', '/#/', '')
                ),
                'validators' => array(
                    array(
                        'Db_NoRecordExists',
                        false,
                        array(
                            'table'        => 'tweepeat_message',
                            'field'        => 'tweepeat_hash'
                        )
                    )
                ),
                'required'    => true
            )
        );
    }    
}

If there is a match I get a message through the regular validation channel saying "A record matching asdf was found", if "asdf" is what you submitted.  Like I said, nice and easy.

Comments

No comments yet...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.