I have only now started playing with CI and the MVC development model, so I have some problems.
I have a db table to dynamically generate menu on a website
The table "menu" looks like this:
id: int
display_name: varchar(50)
parent_id: int
link: varchar(150)
I use CI and Twitter bootstrap CSS framework to gererate menu from DB.
So my model with query gets all objects from the table. The controller passes the resulting array to view, where the following pseudo-code:
if (parent == 0){
echo '<li><a href="$menu_item['link'].'">'.$menu_item['display_name'].'</a></li>';
}
this all works fine for main menu.
However what i want to achieve is:
if the record with id, let say "2", has subitems (records with parent_id = 2 exist id table) that generate the dropdown element, applying css class dropdown to the li element, and then within that li element show results of a query WHERE parent_id = 2
I hope you understand what I'm after. I'm clearly not meant to be a teacher explaining things to people :)
This is what I managet to get so far:
Model:
class MainMenu_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function get_menuitems($parent)
{
$query = $this->db->get_where('tbl_menus', array('parent_id' => $parent));
return $query->result_array();
}
public function get_submenuitems($parent)
{
$query = $this->db->get_where('tbl_menus', array('parent_id' => $parent));
return $query->result_array();
}
}
Controller: (i know controller is not supposed to generate html, but that's for testing only)
class MainMenu extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('MainMenu_model');
}
public function index()
{
$data['parent'] = $this->MainMenu_model->get_menuitems(0);
foreach ($data['parent'] as $items){
echo $items['display_name'].'(';
$data['child'] = $this->MainMenu_model->get_menuitems($items['id']);
foreach ($data['child'] as $offspring){
echo $offspring['display_name'].',';
}
echo ');';
}
$this->load->view('templates/header');
$this->load->view('mainmenu/index', $data);
$this->load->view('templates/footer');
}
}
the controller echoes hierarchy how it should be - item and children in bracket (if there are any). When I do print_r($parent) in view page I get the main items but print_r($child) brings nothing.