K
K
killary2021-05-27 15:09:49
Yii
killary, 2021-05-27 15:09:49

Validation in AR model or in form!?!?

Greetings.
I asked myself the following question...
There is an AR model and a web admin panel in which you can create, change or delete this model.
And there are several ways to implement it:

1. We describe the validation rules directly in the AR model. And we use the same AR model as a form model.
Everything seems to be fine, but the Yii documentation and the community seem to be saying that validation should be at the form level and not the model level. And in general it is desirable to always use forms.

2. We remove the validation from the AR model and make new and update form models. We do validation in fom models. Everything seems to be fine, a classic example. But, there was a problem - the AR model has a unique field, and if at the AR model level it is easy to validate it with the 'unique' validator, then in the form model some kind of 'not exists' validator is needed, but in Yii for some reason this is not. So either make your own, or look for other options.

3. Experiment with something similar - leave the validation at the level of the AR model. And the form models inherit from the AR model.

4. Another experiment is to leave the validation at the AR model level, and pass validation errors to the AR model in the form model.

In general, all 4 options seem to be working, but with their own drawbacks.
But there is a feeling that there should be some kind of more harmonious solution.

Share your experience, colleagues)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
werdender, 2021-05-27
@werdender

If your form is based on an AR class, then you just need to inherit it from it, redefining, if necessary, the validation rules and adding the necessary logic. If you need to validate data that is not related to the database (for example, a login form), then the form is inherited from yii\base\Model and the validation rules are described in it. Those. the answer to your question depends on what data you are validating.
This is the common way, as described in the yii documentation , but in the real world, every SSBN is:

When you create a form based on a model, you need to define what the model is. The model can be based on the Active Record class, which describes some data from the database, or on the Model base class (derived from yii\base\Model), which allows you to use an arbitrary set of form elements (for example, a login form).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question