CodeIgniter Forums
Model validation - localized labels - 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: Model validation - localized labels (/showthread.php?tid=86191)



Model validation - localized labels - Rinart - 01-19-2023

I'm trying to validate input data when creating a new client but I want to properly display localized messages along with the field names:

Code:
// Validation
protected $validationRules      = [
    'fio'        => [
        'label' => lang('Clients.colFio'),
        'rules' => 'required|min_length[5]|max_length[150]|is_unique[clients.fio]',
    ],
    'tel'        => [
        'label' => lang('Clients.colTel'),
        'rules' => 'required|min_length[7]|max_length[20]|regex_match[/^\\+?[0-9 ]+$/]',
    ],
    'date_birth'  => [
        'label' => lang('Clients.colDateBirth'),
        'rules' => 'required|valid_date'
    ],
];

The problem is that apparently it's not allowed to call functions in protected variable definition in a model class (I'm getting "Fatal error: Constant expression contains invalid operations").
Currently I'm using the following workaround. Is it ok?

Code:
$rules = $model->getValidationRules();
$rules['fio']['label'] = lang('Clients.colFio');
$rules['tel']['label'] = lang('Clients.colTel');
$rules['date_birth']['label'] = lang('Clients.colDateBirth');
$model->setValidationRules($rules);

And how do I display model errors in a place where form validation errors usually are?
Right now I'm using the following:

Code:
if ($model->insert($inputs, false) === false) {
    $errors = $model->errors();
    $validation = Services::validation();
    foreach ($errors as $field => $error) {
        $validation->setError($field, $error);
    }
}



RE: Model validation - localized labels - kenjis - 01-19-2023

You can move the initialization of $validationRules to the initialize() method of the model.