How to create a Widget - Recent Comments widget

3 followers

Here's a simple way to create a Recent comments showing widget to be used in your templates. The idea is just to highlighting your blog's new comments.

Step 1: - Creating a Widget Component

components/Comments.php

Yii::import('zii.widgets.CPortlet');
 
class Comments extends CPortlet
{
    public $title='Recent Comments';
    public $maxComments=10;
 
    public function getComments()
    {
        return Comment::model()->findRecentComments($this->maxComments);
    }
 
    protected function renderContent()
    {
        $this->render('comments');
    }
}

step 2 :- in components/views/comments.php

here comes the view file ('comments')

<ul>
<?php 
$comments = $this->getComments();
 
foreach($comments as $comment)
{
    echo "<li> {$comment->fieldName}</li>";
}
?>
</ul>

Step 3 :- in model model/Comment.php

public function findRecentComments($limit=null)
    {
        return $this->findAll(array(
            'order'=>'t.create_time DESC',
            'limit'=>$limit,
        ));
    }

Final step, Step 4 :- In your layout

eg:/protected/views/layouts/column2.php

$this->widget('Comments', array(
                'maxComments'=>10,
            ));

Happy Coding Yes It Is ........

Total 2 comments

#17578 report it
Rohit Suthar at 2014/07/04 07:55am
Nice..

it's nice code..

#17449 report it
Daniel Galvan at 2014/06/13 03:32pm
Very Good

Simple but complete and clear example.

Leave a comment

Please to leave your comment.

Write new article