METS BLOG

METS BLOG

Yii two Models in one View

Adding two models to one view is pretty easy if they have a relation.
I’ll assume you know how to generate CRUD with gii und use the example in Relational Objects

I’ll generate CRUD for both Models which will generate Controllers and Views for models,
after this you should be ok generating controllers seperately and creating your own views

Step 1 – Generate CRUD

  1. Generate CRUD for JUser with gii
  2. Generate CRUD for JProfile with gii

Step 2 – Controller

Lets say I want to include the information from JProfile in JUser view,
since each user has his/her own profile.

  1. Open JUserController.php under controllers folder
  2. Change the actionView function
  3. Instead of sending only the model information to the view I send the model and also one of the model in its relations, in this case JProfile
  4. This is much easier because these objects are in relation
  5. You will eventually realise that same logic can be applied to create etc 🙂
  6. In case theres no relation you just have to get the model using some other mean like another controller

Step 3 – View

  1. Open view.php under views/JUser folder
  2. Change the view to look like this

Leave a Reply

Your email address will not be published. Required fields are marked *