CodeIgniter Forums
Validation Placeholders being ignored for is_unique - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: Validation Placeholders being ignored for is_unique (/showthread.php?tid=72243)



Validation Placeholders being ignored for is_unique - NiteRaven - 11-26-2018

https://codeigniter4.github.io/CodeIgniter4/models/model.html#validation-placeholders

PHP Code:
protected $validationRules = [
 
   'email' => 'required|valid_email|is_unique[users.email,id,{id}]'
]; 

looking at the is_unique method in Rules.php it does not appear {id} is being converted to it's corresponding value in $data.

Thanks,
Kyle


RE: Validation Placeholders being ignored for is_unique - NiteRaven - 11-26-2018

Something like this?

PHP Code:
    public function is_unique(string $str nullstring $field, array $data): bool
    
{
        
// Grab any data for exclusion of a single row.
        
list($field$ignoreField$ignoreValue) = array_pad(explode(','$field), 3null);

        
// Break the table and field apart
        
sscanf($field'%[^.].%[^.]'$table$field);

        
$db Database::connect();
        
        
$row $db->table($table)
                 
 ->select('1')
                 
 ->where($field$str)
                 
 ->limit(1);

        if ( ! empty(
$ignoreField) && ! empty($ignoreValue))
        {
            if (
$ignoreValue[0] == '{') {
                
$key substr($ignoreValue1, -1);
                
                if (isset(
$data[$key]))
                    
$ignoreValue $data[$key];
            }
            
            
$row $row->where("{$ignoreField} !="$ignoreValue);
        }

        return (bool) (
$row->get()
                        ->
getRow() === null);
    } 



RE: Validation Placeholders being ignored for is_unique - NiteRaven - 12-06-2018

Any updates on this? This comes in to play when post data needs validating and you call a validation rule set by name... instead of by array... so you can't actually pass {$id}:

$this->validate('user')

The is_unique rule does not check for post data... it only looks if the value was passed in the check.

Look at my example to see how I worked around this... but I'm not sure if there is a better way?