CodeIgniter Forums
Call function in model before validation - 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: Call function in model before validation (/showthread.php?tid=74879)



Call function in model before validation - RobT - 11-19-2019

Hi guys,
I have a model with the following validation rule.

PHP Code:
'slug'  => 'is_unique[products.slug,ID,{ID}]|alpha_dash' 

I would like to automatically generate a slug when none is provided, so I added:

PHP Code:
protected $beforeInsert = ['generateSlug'];

protected function 
generateSlug(array $data)
    {
        if (empty(
$data['data']['slug']))
        {
            
$data['data']['slug'] = url_title($data['data']['name'], '-'true);
        }

        return 
$data;
    } 


The problem seems that validation rules are evaluated before `beforeInsert` callback is called.

Could you help me?
Thanks.


RE: Call function in model before validation - littlej - 01-06-2020

Hello,

The simplest solution would be to remove the validation rule you have set, that is blocking the process (probably something like "required", add "permit_empty" instead). Then do the validation yourself like you are doing already in your function.

As I see it, this is not really a "validation" if the provided data is always "valid". It seems to be more like a "filter" function.