Creating Recent Comments Portlet

In this section, we create the last portlet that displays a list of comments recently published.

1. Creating RecentComments Class

We create the RecentComments class in the file /wwwroot/blog/protected/components/RecentComments.php. The file has the following content:

class RecentComments extends CPortlet
    public $title='Recent Comments';
    public $maxComments=10;
    public function getRecentComments()
        return Comment::model()->findRecentComments($this->maxComments);
    protected function renderContent()

In the above we invoke the findRecentComments method which is defined in the Comment class as follows,

class Comment extends CActiveRecord
    public function findRecentComments($limit=10)
        return $this->with('post')->findAll(array(
            'order'=>'t.create_time DESC',

2. Creating recentComments View

The recentComments view is saved in the file /wwwroot/blog/protected/components/views/recentComments.php. It simply displays every comment returned by the RecentComments::getRecentComments() method.

3. Using RecentComments Portlet

We modify the layout file /wwwroot/blog/protected/views/layouts/column2.php to embed this last portlet,

<div id="sidebar">
    <?php if(!Yii::app()->user->isGuest) $this->widget('UserMenu'); ?>
    <?php $this->widget('TagCloud', array(
    )); ?>
    <?php $this->widget('RecentComments', array(
    )); ?>

Total 1 comment

#15562 report it
mi.sarah at 2013/11/21 09:42am
Content of the View recentComments

The content from the demo blog under /protected/components/views/recentComments.php looks like the following:

  <?php foreach($this->getRecentComments() as $comment): ?>
  <li><?php echo $comment->authorLink; ?> on
      <?php echo CHtml::link(CHtml::encode($comment->post->title), $comment->getUrl()); ?>
  <?php endforeach; ?>

Leave a comment

Please to leave your comment.