2

I 'm writing a custom component and I already get done the router.php:

defined('_JEXEC') or die;
function empresaBuildRoute(&$query) //Esta función divide la url y se trae las variables.
{
    $segments = array();
    if (isset($query['view']))
    {
        $segments[] = $query['view'];
        unset($query['view']);
    }
    if (isset($query['padre']))
    {
        $segments[] = $query['padre'];
        unset($query['padre']);
    };
    if (isset($query['id']))
    {
        $segments[] = $query['id'];
        unset($query['id']);
    };
    if (isset($query['categoria']))
    {
        $segments[] = $query['categoria'];
        unset($query['categoria']);
    };
    if (isset($query['empresa']))
    {
        $segments[] = $query['empresa'];
        unset($query['empresa']);
    };

    return $segments;
}
function empresaParseRoute($segments) //Esta función reconoce las variables y las reacomoda.
{   

    //print_r($segments); //Si deseas verificar el contenido de la Array "segments".

    $vars = array();
    switch($segments[0])
    {
        case 'actividad': //Verifica las View y según cada una del componente, ordena las variables.
            $vars['view'] = 'actividad';
            $id = explode(':', $segments[2]); //Los segmentos son una array que contiene otra array
            $vars['id'] = (int) $id[0]; //La posicion 0 de la array contenida en la posicion 2 de la array anterior
        break;

        case 'empresa':
            $vars['view'] = 'empresa';
            print_r($segments);
            $categoria = explode(':', $segments[1]);
            $vars['categoria'] = (int) $categoria[0];
            $empresa = explode(':', $segments[2]);
            $vars['empresa'] = (int) $empresa[0];
        break;
    }
    return $vars;
}

It does its job but the url looks like

/actividad/10-hosteleria-y-restaurantes/11-cervecerias

I read a lot but there's just information for remove ID in articles (that's old, joomla 3.x do this by default), nothing about this. Can some one help me with this?

4
  • As far as I understand, you should NOT push id into $segments array. So $segments[] = $query['id']; should be removed from your build() function. Also you need to find the id from the alias by writing some db queries inside your parse() function. eg: $vars['id'] = get_id_from_alias($alias) where $alias is a member of $segments array say $segments[0] that is defined inside your build() function.
    – Farahmand
    Commented Aug 27, 2015 at 22:54
  • I was thinking in something like this. Now you enlighten me a lot. If this is the solution i'll post it here. Commented Aug 29, 2015 at 4:21
  • @Farahmand, thank you, i find the solution, i'll post it here. Commented Aug 29, 2015 at 12:09
  • You're welcome @Ignacio! Glad it helped!
    – Farahmand
    Commented Aug 29, 2015 at 14:59

2 Answers 2

2

I found the solution with the help of @Farahmand, here it is:

<?php

defined('_JEXEC') or die;
function empresaBuildRoute(&$query) //Esta función divide la url y se trae las variables.
{
    $segments = array();

    if (isset($query['view']))
    {
        $segments[] = $query['view'];
        unset($query['view']);
    }
    if (isset($query['padre']))
    {
        $segments[] = $query['padre'];
        unset($query['padre']);
    };
    if (isset($query['id']))
    {
        $segments[] = $query['id'];
        unset($query['id']);
    };
    if (isset($query['categoria']))
    {   
        $cat = explode(':', $query['categoria']); //Variable temporal para guardar solo el alias de la categoria
        if (count($cat) == 2) { //Contar los valores, si son dos es porque existe ID y Alias
            $segments[] = $cat[1];
        } else { //Caso contrario, seleccionar la categoría pues esta contendría solo el ID
            $segments[] = $query['categoria'];
        }
        unset($query['categoria']);
    };

    if (isset($query['empresa']))
    {
        $segments[] = $query['empresa'];
        unset($query['empresa']);
    };
    return $segments;
}

function empresaParseRoute($segments) //Esta función reconoce las variables y las reacomoda.
{   

    print_r($segments); //Si deseas verificar el contenido de la Array "segments".
    $vars = array();
    switch($segments[0])
    {

        case 'actividad': //Verifica las View y según cada una del componente, ordena las variables.
        $vars['view'] = 'actividad';
            $id = explode(':', $segments[2]); //Los segmentos son una array que contiene otra array
            $vars['id'] = (int) $id[0]; //La posicion 0 de la array contenida en la posicion 2 de la array anterior
            break;

        case 'empresa':
            $vars['view'] = 'empresa';

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

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

            $vars['categoria'] = (int) $result;

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

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

            $vars['empresa'] = (int) $empresa;
        break;
    }
    return $vars;
}
?>
  1. Building the route I wrote a temporal variable to explode the query by ':' called $cat. If the query have a Slug, the explode will make an array like this: array([0]=> id, [1]=> alias) else will be array([0]=> id)
  2. Next I make a conditional with a count to know if the array has actually an id and an alias: if (count($cat) == 2) { if this is true it will fill the segment with only the alias content inside of $cat[1]: $segments[] = $cat[1]; else it will fill with $query['categoria']: else { $segments[] = $query['categoria']; }
  3. Inside the parse() in the case 'empresa', wich is my view, I made a DB call for information where I try to find the id when the alias is the listed one inside of $segments[1]:

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

And store that inside of $vars['categoria'] : $vars['categoria'] = (int) $result; for the category id.

  1. For the "empresa" id I find (and I don't know why) that BuildRoute() or ParseRoute() changes the first "-" in an alias for a ":" and broke the DataBase call. To fix this i wrote $empresa_alias = str_replace(":","-",$segments[2]); then instead of use the $segments[1] I used the $empresa_alias variable.
  2. Finally the url now looks like ...com/actividades/empresa/cervecerias/ cerveceria-madriz-cafeteria without id in "cervecerias". I'll repeat the same with the rest of my views. - http://pinto.isalcedo.com/actividades/empresa/cervecerias/cerveceria-madriz-cafeteria

Sorry for my english and I hope this can help a lot o people.

0

Create a menu item for any items you don't want to have an ID shown, at the very least a menu item for the parent category /actividad/10-hosteleria-y-restaurantes in your example then the alias (used to generate the URL) can be set to whatever you want.

3
  • Oh boy, there is so many categories and so many bussiness inside each category... Also the client (the owner of the site) can't handle that. There is not a code solution? Commented Aug 27, 2015 at 16:43
  • @IgnacioSalcedo As far as I know, there is no 'obvious' solution. This has been the single biggest grip as if you want URLs without IDs; the only was seems to be adding them to Menus!
    – sifu
    Commented Aug 27, 2015 at 19:39
  • Sorry, I was not trying to be a douchebag, really sorry if sound like that. I'm doing now some hardcoding, thinking on maybe a .htaccess solution, adding menus is not the solution in this case... I'll update if i find a solution. Commented Aug 27, 2015 at 21:29

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.