Should form models extend the base ActiveRecord model or not?


(Veseliq) #1

This is something I’d love to see in Yii2 cookbook.

We have cases where there are different forms for the same model. For example a User model. A user can register (this is one form), in backend admins can manage the user and their rights and RBAC groups. A user can be able to edit their profile, which might be a different set of fields compared to the register. If we try to do all above in the User model itself and control it with scenarios, it soon becomes messy. Also if we want to send an email for activation or welcome email to the user, both our models and controllers start to become hard to read.

One thing we could do is have different forms for different scenarios. Let’s say RegisterForm and BackendUserForm (where admins can also edit user rights and change username, while users can’t change username). Having separate classes with validation rules to manage this scenarios is definitely cleaner. But should such form extend the User model and be saved or should it extend yii\base\Model and redeclare the User fields again (then define a function save() in the form that sets the fields and saves the base model)?


(Alexander Makarov) #2

I’d extend from yii\base\Model.