I create a dynamic menu in the folder of library in codeigniter framwork.
class Left_menu {
private $ci;
function __construct()
{
$this->ci =& get_instance(); // get a reference to CodeIgniter.
}
function get_company ()
{
$html_out = '';
$company = $this->ci->db->query("select * from perusahaan");
$html_out .= "<ul class='sub_list'>";
foreach ($company->result() as $row)
{
$id = $row->id;
$name = $row->name;
$location = $row->location;
$html_out .= "<a href='".site_url("perusahaan_controller/detailPersahaan/".$id."")."'>";
$html_out .= "<li>".$name."</li>";
$html_out .= "</a>";
}
$html_out .= "</ul>";
$html = $html_out;
//print_r ($html);
return $html;
}
}
And the in the view I call it:
<?php $this->left_menu->get_company(); ?>
However, it doesn't show the menu at all. It does if only I print it, //print_r ($html);
, and the weird is it printed the menu as how I want to return it. (It looks like it turns the return
function into print_r).
You don't need to create a library for this.
Simply use a Model to fetch the data and inject your sidebar into your current controller.
You can do this by creating a partial view called sidebar, and pass it some data from the model, then insert it into your current view.
class Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->model('mymodel');
$data = $this->MyModel->get_data();
// call the sidebar view and pass it some data from model
// at this point the view is in the buffer so it can be manipulated before final output.
$sidebar = $this->load->view('sidebar', array(
'data' => $data
), true);
return $this->load->view('index', array(
'sidebar' => $sidebar
));
}
}
class MyModel extends CI_Model
{
public function __construct()
{
parent::__construct();
}
public function get_data()
{
$query = $this->db->get('perusahaan');
return ( $query->num_rows() > 0 ) ? $query->result() : false;
}
}
<ul class="sublist">
<?php foreach($data as $_data): ?>
<li id="<?php echo $_data->id;?>">
<a href="<?php echo ".site_url('perusahaan_controller/detailPersahaan/')."/".$_data->id.""><?php echo xss_clean($_data->name);?></a>
</li>
<?php foreach; ?>
</ul>
<aside class="sidebar">
<?php echo $sidebar; ?>
</aside>
<div>
//... content
</div>