2

I have a Client ID, and a Unique Client hash. When I register these data, it works fine. Just to be clear, I do not generate the hash.

The code I use to validate if that unique hash already exists:

protected function _getValidator($field)
{
    return array(
        'Db_NoRecordExists',
        true,
        array(
            'table' => 'anunciantes',
            'field' => $field,
            'messages' => array(
                'recordFound' => ucfirst($field) . ' "%value%" is registered'
            )
        )
    );
}

But when I have to edit that Client, I want to validate if that hash already exists, and if that hash belongs to that Client.

How I do it? I already tried to get the value of the id by using 'exclude' option of db validator and passing $this->getValue('id'), but that call returns null.

Rondel
  • 4,811
  • 11
  • 41
  • 67
Denis Lins
  • 816
  • 7
  • 22

2 Answers2

0

You have to abb a validator in your form to that field like..

$name->addValidator(
    'Db_NoRecordExists', 
    true, 
    array(
        'table' => 'currencies',
        'field' => $field,
        'messages' => array( "recordFound" => "This Client Id already exists in our DB") ,
        'exclude' => array(
             'field' => 'id',
             'value' => $this->_attribs['id']
         )
    )
);
Nilesh Gupta
  • 367
  • 1
  • 2
0

To validate if the hash already exists and belongs to a specific user, you can use the following validator with a custom exclude condition. I assume that the hash is a hidden text field containing the hash from the database.

protected function _getEditValidator($field, $userId, $db = null)
{
    if ($db == null) $db = Zend_Db_Table::getDefaultAdapter();

    array(
        'Db_RecordExists',
        true,
        array(
            'table' => 'anunciantes',
            'field' => $field,
            'exclude' => $db->quoteInto('user_id = ?', $userId)
        )
    );
}

This will check to make sure that the hash contained in the element matches the hash in the database that belongs to user_id. We are overriding the exclude option to make it so the hash value must match what is set for the given user id.

The query should look roughly like this:

SELECT `users`.`db_hash_col` FROM `users` WHERE (`db_hash_col` = :value) AND (user_id = 1234) LIMIT 1

You will need to use some logic to swap the validators when editing a user vs creating a user. You might set it like this:

if ($editing) {
    $this->getElement('hash')
         ->setValidators(
             array($this->_getEditValidator('db_hash_col',
                                            $this->getElement('id')->getValue());
}

Also, in your question you mentioned using $this->getValue('id'); I believe this should actually be $this->getElement('id')->getValue().

Hope that helps.

drew010
  • 68,777
  • 11
  • 134
  • 162