How to Update 2 models in 1 form?

:rolleyes: Good Day

I want to know how to UPDATE 2 MODELS in a SINGLE FORM

For example I Have 2 models., USER and USER_PROFILE

USER ( user_id, username, password )

USER_PROFILE ( user_id, fullname, birthday )

This 2 MODELS are in a SINGLE FORM… I know already how to insert them at the same time ,

What i want to know is how to update them in a single form provided that when u CLICK UPDATE from USER,

it will also fetch data from USER_PROFILE and set them in the form so i can update them????

any idea??

Thanks…:D

The concept you want is called a ViewModel, which is a model created for the purposes of a special view.

You create a model in the normal way but it inherits from yii\base\Model instead of yii\db\ActiveRecord. In this model, you explicitly create public properties that you want to use on your form (probably all the properties from both database models). You can use the normal rules and labels functions and glue this model to a View in exactly the same way as normal.

When you call the action to save the model, the controller needs to create a new one of your view model classes, populate it using $_POST as normal but then rather than calling a built-in function like save(), the controller calls a function that you create in the ViewModel (which you might call save) and which will create each of the two database models, copy the data across from the properties in the view model and then call save on each of the database models.

Hopefully that’s clear! You can look in LoginForm.php for an example of a ViewModel, which uses User under the covers but is not directly attached to the User database table.