CodeIgniter Forums
beforeInsert Validation for unique data - 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: beforeInsert Validation for unique data (/showthread.php?tid=78501)



beforeInsert Validation for unique data - bulentsakarya - 01-30-2021

Hi.

I want to verify again before saving the content in the model file.

I want the category name on the form to check if it is in the same sector.

There may be a category with the same name in different sectors. So I can't set is_unique directly.

How can I add the custom error message as well?


PHP Code:
    protected $validationRules = [
        'sector_id' => 'required',
        'category' => 'required'
    ];
    
    
protected $validationMessages = [
        'sector_id' => [
            'required' => 'Select sector',
        ],
        'category' => [
            'required' => 'Select '
        ]
    ];

    protected $beforeInsert = ['checkCategory'];
    
    
protected $beforeUpdate = ['checkCategory'];
    
    
protected function checkCategory(array $data)
    {

        $check_it $this->where('category'$data['data']['category'])
                         ->where('sector_id'$data['data']['sector_id'])
                         ->first();

        if (!empty($check_it)) {

            $fieldName 'category';
            $fieldRules 'is_unique[categories.category]';
            
            $this
->setValidationRule($fieldName$fieldRules);

        }
        
        
return $data;