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);
}
}