1

So I have read https://docs.joomla.org/Supporting_SEF_URLs_in_your_component and looked at examples both online and in com_content but I still cannot get this routing thing down 100%.

I would like to know if the way I'm doing it is correct or if there is a better or simpler way to achieve the same thing.

I want to create friendly URL's without the id. The link I provided above I went through the simple solution and got it working except I couldn't get rid of the id: at the front of the alias (in the slug). I'm not after a complex solution as the component only has a list view and a single item view - no categories etc views.

So I believe I found this on a forum a while ago and this was the closest I got to having a effective routing system.

The problem is if a user types in an incorrect url, eg myurl.com/menuitem/incorrectalias rather than displaying a 404 error page it queries the database for every item that could potentially be displayed on this page causing the browser to crash. Is there any way to display the error page for the mentioned scenario?

class mycompoenentRouter extends JComponentRouterBase
{
  public function build(&$query)
  {
     $segments = array();
     if (isset($query['id']))
     {
       $id = explode(':', $query['id']);
       $segments[] = $id[1];
       unset($query['id']);
     }
     unset($query['view']);
     return $segments;
  }

  function parse(&$segments)
  {
    $vars = array();
    $app = JFactory::getApplication();
    $menu = $app->getMenu();
    $item = $menu->getActive();

    switch ($item->query['view'])
    {
      case 'list':
      $vars['view'] = 'item';

      $db = JFactory::getDbo();
      $query = $db->getQuery(true);
      $query->select('id');
      $query->from($db->quoteName('#__table'));
      $query->where($db->quoteName('alias')." = ".$db->quote($segments[0]));

      $db->setQuery($query);
      $result = $db->loadResult();

      $vars['id'] = (int) $result;
      break;
    }

    return $vars;
  }
}

1 Answer 1

1
if(empty($result)){
    JError::raiseError(404, JText::_('COM_YOURCOMPONENT_ITEM_NOT_FOUND'));
}
1
  • Thank You. I did manage to figure it out but it's good to know I got it right!
    – Alex Mehan
    Aug 30, 2017 at 12:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.