How to create a Widget - Recent Comments widget

You are viewing revision #3 of this wiki article.
This is the latest version of this article.
You may want to see the changes made in this revision.

« previous (#2)

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 ........