rsanchez/resource_router

category group matching in segment_1

carolinecblaker opened this issue · 5 comments

My code:

$config['resource_router'] = array(
'/restaurants' => 'directory/index',
'/shopping' => 'directory/index',
);

The above wildcards are actually names of category groups. Since category groups don't get the same url-matching love that categories do, is there a way of passing a variable for the category group id's without matching it to a segment?

Sure, you can do something like this:

$config['resource_router'] = array(
    '(restaurants|shopping)' => function ($router, $wildcard) {
        $query = ee()->db->get_where('category_groups', array('group_name' => $wildcard->value));
        $category_group = $query->row('group_id');
        $router->setGlobal('category_group', $category_group);
        $router->setTemplate('directory/index');
    },
);

And then in your template you will have an early parsed variable {category_group} which you can use:

{exp:channel:entries
    channel="foo"
    dynamic="no"
{if category_group}
    category_group="{category_group}"
{/if}
}

You're a genius.

I realize this is just PHP help, but I'm going to ask anyway because the above trips up on my categories with spaces like "Day Trips"

I tried array('group_name' => str_replace('_', ' ', $wildcard->value))) and this doesn't appear to be enough.

Are you able to recommend a thing to do here so that the wildcards pull appropriately?

It's unfortunate that EE doesn't provide a category group short name, so all you've got to go on is the group name. But, CI does have a useful function that will work here, I think. It's the humanize function of the inflector helper.

$config['resource_router'] = array(
    '(restaurants|shopping|day_trips)' => function ($router, $wildcard) {
        ee()->load->helper('inflector');
        $group_name = humanize($wildcard);
        $query = ee()->db->get_where('category_groups', array('group_name' => $group_name));
        $category_group = $query->row('group_id');
        $router->setGlobal('category_group', $category_group);
        $router->setTemplate('directory/index');
    },
);

Thank you!!