Hello everyone!
Just curious if it’s okay to add some custom fields to a model, fields that have nothing to deal with the database.
The problem is that I have to add a dropdown list to a view which has to have a data array from another model. For example I’ve got two model which are Client and Registration. The Registration model has all the license keys that’s been currently using by users. I need to do something like this in the Client model:
class Client extends \yii\db\ActiveRecord
{
public $all_license_key = Registration::find()->select([‘license_key’])->indexBy(‘id’)->column();
…
To me it feels like there’s gotta be a better way to do this. Maybe using behaviors or something would be more appropriate
Despite not knowing if it really is really the best practice / way…
I usually create specific models for each purpose.
Means in your example:
There are the “Db / ActiveRecord Models” which are doing the database related stuff / calculations / methods which are commonly used to interact with the DB… and then I would create a new model for example “RegistrationForm” and there I would tie the functionality for the Form together… means the RegistrationForm Model either extends or simply uses the Registration / Client Models / holds the validation rules just for the form / provides methods for the drop downs / processes the actual form data if additional transformation is needed.
You can see an example for that even in the yii2-advanced template here:
This “LoginForm” Model does nothing else than handling the login of users by using the “User” Model and providing methods just for the login.
That way you keep everything separated (db, forms, views) and have kind of “single responsibility” for each Model you write… For me that works quite well and it is fore sure better than having a single “One fits multiple purposes” model.