2

ZF2 docs show the following example in terms of using Db\RecordExists validator with multiple columns.

$email     = 'user@example.com';
$clause    = $dbAdapter->quoteIdentifier('email') . ' = ' . $dbAdapter->quoteValue($email);
$validator = new Zend\Validator\Db\RecordExists(
    array(
        'table'   => 'users',
        'field'   => 'username',
        'adapter' => $dbAdapter,
        'exclude' => $clause
    )
);

if ($validator->isValid($username)) {
    // username appears to be valid
} else {
    // username is invalid; print the reason
    $messages = $validator->getMessages();
    foreach ($messages as $message) {
        echo "$message\n";
    }
}

I’ve tried this using my own Select object containing a more complex where condition. However, isValid() must be called with a value parameter.

In the example above $username is passed to isValid(). But there seems to be no according field definition.

I tried calling isValid() with an empty string, but this does not produce the desired result, since Zend\Validator\Db\AbstractDb::query() always adds the value to the statement:

$parameters = $statement->getParameterContainer();
$parameters['where1'] = $value;

If I remove the seconds line above, my validator produces the expected results.

Can someone elaborate on how to use RecordExists with the where conditions in my custom Select object? And only those?

Rob
  • 1,158
  • 1
  • 12
  • 22

1 Answers1

0

The best way to do this is probably by making your own validator that extends one of Zend Framework's, because it doesn't seem like the (No)RecordExists classes were meant to handle multiple fields (I'd be happy to be proven wrong, because it'd be easier if they did).

Since, as you discovered, $parameters['where1'] is overridden with $value, you can deal with this by making sure $value represents what the value of the first where should be. In the case of using a custom $select, $value will replace the value in the first where clause.

Here's a hacky example of using RecordExists with a custom select and multiple where conditions:

$select = new Select();

$select->from('some_table')
    ->where->equalTo('first_field', 'value1') // this gets overridden
    ->and->equalTo('second_field', 'value2')
;

$validator = new RecordExists($select);

$validator->setAdapter($someAdapter);

// this overrides value1, but since isValid requires a string, 
// the redundantly supplied value allows it to work as expected
$validator->isValid('value1');

The above produces the following query:

SELECT `some_table`.* FROM `some_table` WHERE `first_field` = 'value1' AND `second_field` = 'value2'

...which results in isValid returning true if there was a result.

jabbascript
  • 345
  • 1
  • 6
  • 13