Welcome Guest, Not a member yet? Register   Sign In
Model validation - localized labels
#1

(This post was last modified: 01-19-2023, 10:29 AM by Rinart.)

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);
    }
}
Reply
#2

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




Theme © iAndrew 2016 - Forum software by © MyBB