In this tutorial, we try to make different scenario. Show last post and the number of comments in that post. The code must be flexible. We can be back to display list or last post without change any code anymore. If can do it, it is realy named flexible!
First, we modify "mod_hello.php" within joomla/modules/mod_hello. Update like following code:
<?php
defined('_JEXEC') or die('Restricted access');
require(dirname(__FILE__).DS.'helper.php');
$last = $params->get('last' , 1);
if($last)
{
$rows = modHelloHelper::lastHello($params);
}
else
{
$rows = modHelloHelper::getHello($params);
}
require(JModuleHelper::getLayoutPath('mod_hello','lastpost'));
?>
From the code, we need method lastHello within helper. This method for retrieve last post from database. Open helper.php, and add following code:
function lastHello(&$params)
{
$db =& JFactory::getDBO();
$query = "SELECT id, message FROM
#__hello ORDER BY id DESC LIMIT 1 ";
$db->setQuery( $query );
$rows = $db->loadObjectList();
if ($db->getErrorNum()) {
JError::raiseWarning( 500, $db->stderr(true) );
}
return $rows;
}
For count number of comments, we need method named "countComment" at helper. Add following code to helper.php.
function countComment($item)
{
$db =& JFactory::getDBO();
$query = "SELECT count(1) as total
FROM #__hello_comment WHERE hello_id=".$item;
$db->setQuery( $query );
$rows = $db->loadObjectList();
if ($db->getErrorNum()) {
JError::raiseWarning( 500, $db->stderr(true) );
}
return $rows[0]->total;
}
Just remembering, we call template name "lastpost" at mod_hello: require(JModuleHelper::getLayoutPath('mod_hello','lastpost')).
Now, we create the template. Create a file named "lastpost.php" at joomla/modules/mod_hello/tmpl.
<?php
defined('_JEXEC') or die('Restricted access');
foreach($rows as $row)
{
modHelloHelper::renderHelloComment($row, $params);
}
?>
This call, renderHelloComment() at helper. Add this function to helper class (at "helper.php"):
function renderHelloComment(&$hello, &$params)
{
$total = modHelloHelper::countComment($hello->id);
$link = JRoute::_('index.php?option=com_hello&id='.$hello->id.'&task=view');
require(JModuleHelper::getLayoutPath('mod_hello' , '_hello'));
}
Last, we need modify "_hello.php" for accommodate showing total of comment.
<?php
defined('_JEXEC') or die('Restricted access');
echo 'ID: <A href="'. $link .'">'.$hello->id.'</A> </br>';
echo $hello->message;
echo "</br>";
if((int)$total > 0){
echo "<i>".$total." comments</i>";
echo "</br>";
}
?>