[eluser]MT206[/eluser]
Ok I know this shouldn't be as hard as I am making it but I have been having a lot of trouble getting this simple category system working. Just like any job/marketplace/product website, I will have multiple categories and then sub categories. I have a categories table with the fields: 'id', 'title', 'parent_id'. I would like to have the routes be like:
Top level categories:
mysite.com/categories
Sub-level categories:
mysite.com/categories/arts_crafts
Sub-sub categories:
mysite.com/categories/arts_crafts/painting
The problems I am facing are:
1) I don't know how to get the parent id for an item if the title is not unique
2) If a title is something like 'arts & crafts' I have been converting it into a proper url using something like: url_title(strtolower($row['title']),'underscore'). The problem with this is that it strips the '&' and as such I cannot find the id again.
Here is my code for reference:
MODEL:
Code:
function get_categories($parent_id) {
$this->db->select('title')->from('categories')->where('parent_id', $parent_id);
$this->db->order_by('title', 'asc');
$category = $this->db->get();
$result = $category->result_array();
return $result;
}
CONTROLLER:
Code:
public function categories($id='0')
{
$this->load->helper('url');
$this->load->helper('categories');
$this->load->model('categories_model');
$menu = $this->categories_model->get_categories($id);
$data['menu'] = buildMenu($menu);
$this->load->view('categories_view', $data);
}
HELPER:
Code:
function buildMenu($categories){
$menu = "<ul class='cat_menu'>";
foreach($categories as $row){
$menu .= "<li>" . anchor( current_url() . "/" . url_title(strtolower($row['title']),'underscore'), $row['title']) . "</li>";
}
return $menu . "</ul>";
}
VIEW:
Code:
<html>
<head>
<title>Categories View</title>
</head>
<body>
<?php echo anchor(base_url(), 'Home'); ?>
<h1>Categories</h1>
<?php echo $menu; ?>
</body>
</html>