rsanchez / resource_router

Resource Router for ExpressionEngine
MIT License
48 stars 12 forks source link

category group matching in segment_1 #5

Closed carolinecblaker closed 10 years ago

carolinecblaker commented 10 years ago

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?

rsanchez commented 10 years ago

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}
}
carolinecblaker commented 10 years ago

You're a genius.

carolinecblaker commented 10 years ago

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' => strreplace('', ' ', $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?

rsanchez commented 10 years ago

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');
    },
);
carolinecblaker commented 10 years ago

Thank you!!