Unique Validator

Unique Validator

rf1234rf1234 Posts: 2,991Questions: 87Answers: 421
edited February 2020 in Editor

I wanted to use the built-in "unique" validator for Editor but I didn't know how to use it conditionally: The field may have the values "0", "1" and "2". Only the "2" must be unique in the database. The "0"s and "1"s are occuring many times.

I ended up using the code below. Is there a way to use the built-in validator here?

if ($lang === 'de') {     
    $msg[0] = 'Feld darf nicht leer sein.'; 
    $msg[1] = 'Es kann nur einen Marktplatz Betreiber geben.';
} else {
    $msg[0] = 'Field may not be empty.';
    $msg[1] = 'There can only be one marketplace operator.';
}
.............
Field::inst( 'creditor.type' )
    ->validator( function ( $val, $data, $opts ) use ($msg, $db) {
        if ( $val == '2' ) { //marketplace operator: there is only one!
            $row = $db->raw()
                ->exec('SELECT COUNT(*) FROM `creditor` WHERE `type` = 2')
                ->fetch(PDO::FETCH_ASSOC);
            if ( (bool)$row["COUNT(*)"] ) {
                return $msg[1];
            }
        }
        return true;
    } ), 

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin
    Answer ✓

    No sorry - the built in unique validator doesn't handle special cases like that. You'd need a custom function such as you have done.

    Allan

This discussion has been closed.