Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JRoute::_() in Joomla administrator

I have a custom component I'm working on and I'm writing an import script which is running in the administration area. I have the following code:

$newUrl = ContentHelperRoute::getArticleRoute($import->article_id.':'.$import->alias, $import->catid);
$newUrl = JRoute::_($newUrl);

the first part works returning similiar to this:

index.php?option=com_content&view=article&id=45:joomla-sociable-and-sharethis-module&catid=18

the second part shows it like this:

/administrator/index.php?option=com_content&view=article&id=45:joomla-sociable-and-sharethis-module&catid=18

Both of the above urls are as you'd expect the component com_content to render these urls as if I wanted to use them within the administration area.

Any idea how to force JRoute to work as it would when used in the frontend?

NB: This is being used within a controller of my component, if it makes any difference and I'm including require_once (JPATH_SITE . '/components/com_content/helpers/route.php');

like image 570
udjamaflip Avatar asked Jul 19 '11 11:07

udjamaflip


3 Answers

For those who find this on Google and struggle with using JRoute::_() and contentHelper::getArticleRoute().

$newUrl = ContentHelperRoute::getArticleRoute($import->article_id.':'.$import->alias, $import->catid);

// better will be check if SEF option is enable!
$router = new JRouterSite(array('mode'=>JROUTER_MODE_SEF));
$newUrl = $router->build($newUrl)->toString(array('path', 'query', 'fragment'));
// SEF URL !
$newUrl = str_replace('/administrator/', '', $newUrl);
//and now the tidying, as Joomlas JRoute makes a cockup of the urls.
$newUrl = str_replace('component/content/article/', '', $newUrl);
like image 169
udjamaflip Avatar answered Oct 19 '22 05:10

udjamaflip


Here's a snippet that will work for Joomla 3.6

$routerOptions = [];
if (JFactory::getConfig()->get('sef')) {
    $routerOptions['mode'] = JROUTER_MODE_SEF;
}
$siteRouter = JRouter::getInstance('site', $routerOptions);
$link = $siteRouter->build($yourRoute)->toString();
$link = preg_replace('#^/administrator#', '', $link);
like image 41
Valery Avatar answered Oct 19 '22 05:10

Valery


A nicer solution would be to create a new router instance, so, the code will be something like this:

$app    = JApplication::getInstance('site');
$router = &$app->getRouter();    

$newUrl = ContentHelperRoute::getArticleRoute($import->article_id.':'.$import->alias, $import->catid);

$newUrl = $router->build($newUrl);
$parsed_url = $newUrl->toString();
$parsed_url = str_replace('/administrator', '', $parsed_url);

This way you will always obtain the right URL for the item, no matter if it is a joomla article, K2 article, etc...

** Notice that depending on the type of the item ( k2, joomla, etc) , $newUrl should be obtained with the consequent method.

like image 34
Alberto S. Avatar answered Oct 19 '22 06:10

Alberto S.