Friday, July 25, 2008

How to get the active component in Joomla! 1.5.x

For some time now I have been struggling to figure out how to get the active component in Joomla! 1.5.x without going through the GET/POST Requests. This problem was specifically for the frontpage.

What happens on the frontpage is that it is not possible to echo JRequest::getVar('option') and have the code tell you that you are on the frontpage. Instead the text that will be displayed will simply display com_content, which is the component for articles.

After searching throught the Joomla! Document Wiki I stumbled upon the solution; totally by chance I might add.

How to determine if the user is viewing the front page

The above document shows this piece of code:
$menu = & JSite::getMenu();
if ($menu->getActive() == $menu->getDefault())

echo 'This is the front page';
But what does the code actually do?

JSite::getMenu() returns a JMenu class called $menu that is inherited from the JObject class.

$menu->getActive() and $menu->getDefault() returns objects of the active and default menu items (by id).

If the active object is the same as the default object then naturally it must be the front page.

For other components the simplest option will still be to use the JRequest object to get the component name.

e.g. JRequest::getVar('option')
Note: I have not tested the above code with Search Engine Friendly URLs yet since they may, or may not, make a difference.