Welcome Guest, Not a member yet? Register   Sign In
Database driven menu?
#1

(This post was last modified: 02-21-2015, 09:27 PM by jlp.)

How to create a database driven Menu and autoload this on every pages/Controllers of project?
Reply
#2

I suppose your menu will consist of menu text and a URL to go to when you click on the menu text. You will also want several menus, so I think your database table will look something like this.
Code:
Table: menus

Field   Type         Null  Comments
name    varchar(12)   No   e.g. File, Edit, View, Customers, Vendors, etc.
text    varchar(24)   No   e.g. Add Customer, Print Invoice, etc.
url     varchar(64)   No   e.g. http://mysite.com/ci_app/vendors/edit/32, etc.

In your model file, you will have a function for retrieving all the menu entries for a particular menu name. Something like this.
PHP Code:
public function get_menu($menu_name)
{
 
 return $this->db->query(
 
   'SELECT menus.text AS menu_text,
            menus.url AS menu_url
     FROM   menus
     WHERE  menus.name = ' 
$menu_name ';')->result_array();


In your controller file, perhaps in the constructor, you would have something like this.
PHP Code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

Class 
Your_controller extends CI_Controller {

 
 public $menu = array();

 
 public function __construct()
 
 {
 
   parent::__construct();
 
   $this->load->helper('your_helpers');
 
   $this->load->library('your_libraries');
 
   $this->load->model('your_models');
 
   // for example, to load the vendors menu
 
   $menu $this->menu_model->get_menu('vendors');
 
 

When you call your view file, you'll have to include $menu in the $data array. And in your view file, you'll display the menu using something like this. You could put this code in a partial view file, like sidebar_view.php, something that you load with every view.
PHP Code:
 <div id="sidebar">

 
 <dt>
<?
php
    foreach 
($menu as $name => $url)
 
   {
 
       echo '<dl><a href="'$url '">' $name '</a></dl>';
 
   }
?>
  </dt>

  </div><!-- sidebar --> 

I've chosen to use a definition list to display the menu. You could use any kind of list, or no list at all, but I've read that, semantically, definition list is the best for menus.

You could enhance this with a field for disabled = true/false, so you could disable specific entries. You could also add a field for permissions that determined which kind of user could access the menu.

I hope this is what you were looking for!
Hey, don't work without a PHP debugger. Several free IDEs have this features built in. Two are NetBeans and CodeLobster. Without a debugger, it's like you're driving with a blindfold on -- you are going to crash!
Reply




Theme © iAndrew 2016 - Forum software by © MyBB