Rendering Views and Updating them with Ajax

This wiki article has not been tagged with a corresponding Yii version yet.
Help us improve the wiki by updating the version information.

I wanted to implement a widget that could refresh itself through Ajax without refreshing the whole page. CGridView and CListView are excellent examples of such widgets.

I spent some time trying to understand how a controller renders it’s view(s) and then looked at the actionAdmin and actionIndex actions of an app generated by gii. The views generated by these actions contain CGridView and CListView widgets respectively.

My case study was a simple Dashboard application, where I have two view – left and right in the same page (layout file). The sequence diagram outlines how these two pieces are rendered and how they’re merged with the layout file to generate a page the user will see. I came up with the sequence diagram below.

If the pieces appear unfamiliar to you, you might want to read – Rendering View Files in Yii here (if this link get’s deleted, google the title).

Sequence Diagram

It might be worth mentioning that, the default implementation of the aforementioned widgets, requests the “owning” controller (the one that created the widget) to render it’s entire view again through an Ajax request. When a response arrives, the html response (page) is parsed using jQuery and the section (div) that the widget is interested in is extracted. The widget’s contents are then replaced with the extracted (partial contents) one.

In a typical application’s controller, where one might be displaying several models/views, it might make sense to write a controller that returns just the partially rendered view without any layout applied. This should cut down some time for you depending on how complex your views/models are. This approach, if thought out carefully should also maximize code sharing.

If I have provided inaccurate information, please feel free to comment and let me know.