Thursday, June 9, 2011

Include an external file in Joomla?

you need to add an external file beside joomla file system in a module and component. In this case, your external file can't use the joomla libraries easily. Following is the way to use the external file.
Add following 10 lines of code on top of your external file.

define( '_JEXEC', 1 );
define('JPATH_BASE', dirname(__FILE__));
define( 'DS', DIRECTORY_SEPARATOR );
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
$mainframe =& JFactory::getApplication('site');
$mainframe->initialise();
/* If you need to use database object, add following line too */
$db=JFactory::getDBO(); // use this $db object for database related operation

Now, use this file as normal joomla file. You can include the joomla libraries files as per the requirement also.

Joomla –loadObjectList and foreach to get list

The database class contains many methods for working with a query’s result set. One of the most useful one would be loadObjectList. The syntax of loadObjectList is: loadObjectList ( $key ), this returns an array of database objects using the current SQL query. Returns false if the query fails. If the $key parameter is set, the array is indexed using the values of the field specified by key. Otherwise, the array is indexed sequentially.

The reason I say this is a really handy function is because we always retrieves a list of results belongs to a certain category. For example, if we want to get all category titles from database jos_categories where section equals to 1, and list them out. This can be done by using the following method:


// Get a database object
$db = JFactory::getDBO();
$query = "SELECT * FROM #__categories
WHERE section = 1";
// Executes the current SQL query string.
$db->setQuery($query);
// returns the array of database objects
$list = $db->loadObjectList();
// create the list of titles
foreach ($list as $item) {
$item_title = $item->title;
echo $item_title.'
'
;
}