The Yii2 documentation tells you that when working with forms you need to inherit from the Model class .

<?php namespace app\models; use yii\base\Model; class EntryForm extends Model { public $name; public $email; public function rules() { return [ [['name', 'email'], 'required'], ['email', 'email'], ]; } } 

validation rules are set up here

The question is , if this data is valid, how will it be correctly recorded in the database? Do I need to change the inheritance from model to ActiveRecord? Or am I confusing something? The config for working with the database is already configured. Only without Gii please.

    1 answer 1

    Imh in this case, the framework itself is a little confusing, since its validation is an integral part of the model (you will not be able to create and fill out ten validators at the input there). As a result, in cases like the login form, it turns out that you need to have some kind of model in order to conveniently accept input and validate it. But it is obvious that the login form is not the essence of the application and no table in the database corresponds to it through the form. Those. This model is only needed to validate one particular form. Therefore, they propose to inherit from Model and validate the input in this way; in fact, the Model class does not provide anything more of the functionality.

    If, after the work of such a validator model, something needs to be written down somewhere, then this is already confused by the desired ActiveRecord model and saved through its methods. Those. in the case of a login form, update the User field with the handles of the desired field and save it via User :: save ().

    • Thank you thank you thank you. If possible, please show a minimal example. If my model is inherited from Model and I need to write data to the database, how can this be done? The second model to create and there already inherit from ActiveRecord? - Yuri Svetlov
    • Show this here please - this is already messed with the desired ActiveRecord model and saved through its methods. - Yury Svetlov
    • Well, you probably have a User model in the application, for example, when logging in, you need to update its last_logon. because of this, doing an EntryForm asset-record model is wrong. just as usual you need to find the necessary user through the form User :: find (and so on), set him $ user-> last_logon = 1234, and pull $ user-> save () - kroder
    • one
      whether or not to make two models - decide according to the logic of their work, it may well be that you just need one ActiveRecord model, validate everything in it and save it all - kroder
    • one
      in general, in this case, replace the word Model with the word Validator, it can become so clearer. the real models you have are ActiveRecord, is the particular input form part of the ActiveRecord CRUD model, or does this form just do something by itself and require validation - kroder