Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force Joomla JRoute to use the menu item

I'm building a component for Joomla! 2.5 and inside I'm using JRoute::_('index.php?option=com_myapp&view=cpanel') to build all my links. This works, BUT it produces links which look like that:

/component/myapp/cpanel.html

In the menu however I have defined that index.php?option=com_myapp&view=cpanel has an alias of "myapp" so the link should rather be

/myapp/cpanel.html

The component is accessible via this path. If I do that, also all links generated inside will have the /myapp prefix. But for use in a template (special login link) and if the user stumbles upon /component/myapp.... I still want all links to go to /myapp prefix.

How can I force JRoute to use this menu item entry by itself?

like image 523
Martin Müller Avatar asked Jul 10 '14 13:07

Martin Müller


2 Answers

Because I struggled a lot with this issue, here's a quick function I did that will try to find the link based on a menu item. It's mainly based on other answers.

This has only been tested on Joomla 3.5. JRequest is deprecated, so $app->input is used instead. This might be done better, but at least it works for the use I have of it. Hopes it can help other people too !

public static function getRouteMenu($default_url) {
    $db = JFactory::getDbo();
    $app = JFactory::getApplication();
    $jinput = $app->input;

    $db->setQuery('SELECT `id` FROM #__menu WHERE `link` LIKE '. $db->Quote($default_url) .' AND `published` = 1 LIMIT 1' );
    $itemId = $db->loadResult();
    if($itemId) {
        $route = $jinput->getString('return', JRoute::_('index.php?Itemid='.$itemId));
        $route = str_replace('index.php/', '', $route);
    } else {
        $route = $jinput->getString('return', JRoute::_($default_url));
    }

    return $route;
}

The parameter requires a not rewrited link such as : index.php?option=com_content&view=article&id=10. Check your database if you need to be sure about how to build up this link.

like image 91
soenguy Avatar answered Nov 16 '22 20:11

soenguy


//look if there is a menu item set for myapp. if yes, we use that one to redirect
$db  = JFactory::getDBO();
$defaultRedirect = 'index.php?option=com_myapp&view=cpanel';
$db->setQuery('SELECT `id` FROM #__menu WHERE `link` LIKE '. $db->Quote($defaultRedirect) .' LIMIT 1' );
$itemId = ($db->getErrorNum())? 0 : intval($db->loadResult());
if($itemId){
    $rpath = JRequest::getString('return', base64_encode(JRoute::_('index.php?Itemid='.$itemId)));
}else{
    $rpath = JRequest::getString('return', base64_encode(JRoute::_('index.php?option=com_myapp&view=cpanel')));
}

Beware: This is NOT language-safe. It takes the first menu entry found in the db. If you setup different menu aliases for different languages you have to check for the right language in the SQL query, too.

like image 41
Martin Müller Avatar answered Nov 16 '22 21:11

Martin Müller