CodeIgniter Dynamic Menu Loader is not working Properly - php

I am a starter in CodeIgniter. I am creating a small application in Ci where am loading my menu from database .
The database consists of 3 fields (id,menu_Name,menu_link)
I have created a function in Libraries to fetch data from db
Created a controller by loading the library
Am attaching the code which i have created
Code For libraries
Folder Structure ::::---- libraries/Functions.php
function getMenus()
{
$arrRow =array();
$sql = "select * from tbl_menus ";
$res =mysql_query($sql);
if(mysql_num_rows($res) >0) {
while($row= mysql_fetch_object($res)){
$arrRow[] =$row;
}
}
}
Controller Code
public function index()
{
$val_menu = $this->input->post('menu_Name');
$val_link= $this->input->post('menu_link');
$query=$this->db->get_where('tbl_menus',array('menu_Name'=>$val_menu,'menu_link'=>$val_link));
if ($query->num_rows() > 0)
{
$arrRow=$query->row_array();
$data=$arrRow;
}
$data=array('menu_Name'=>$data,'menu_link'=>$data);
$this->load->helper('url');
$this->load->database();
$this->load->view('Header');
$this->load->view('SideMenu',$data);
$this->load->view('Pages/MainPage',$data);
$this->load->view("Footer");
}
My View Code
<?php
$arrMenus=array();
$arrMenus =$this->functions->getMenus();
?>
<div class="container">
<div class="sidebar1">
<?php if(count($arrMenus) >0) {
foreach($arrMenus as $key_menu=>$val_menu) {
$menu_link =$val_menu['menu_link'];?>
<ul class="nav">
//Before Edit
<li><a href="<?=site_url()?>/<?=$menu_link?>" class="lnk"><?=$val_menu['menu_name']?>
//After Edit
<li><?php echo $val_menu['menu_name']?></li>
</a></li>
</ul>
Print_r() result
Array ( [menuId] => 1 [menu_Name] => UserHome [menu_link] => Pages/MainPage )
View is not working properly..ie the view page is not displaying the menu...so i used print_r($arrMenus) inside the controller;..its showing the data...but menu links are left blank .Print_r($arrMenus) in view page displaying error that conversion problem

Try this
foreach($arrMenus->result() as $key_menu=>$val_menu)

Related

Displaying the page titles based on the pages dynamically in codeigniter php

How to display page titles dynamically based on the pages displayed.
Hi i am having a site developed in codeigniter php but the problem is need to display page titles dynamically based on the pages.These pages titles should be fetched from database.Can anyone have any idea how to do this.
Controller:
public function index()
{
$config = array();
$config["base_url"] = base_url('testimonial/index');
$config['total_rows'] = $this->testimonial_model->record_count();//here we will count all the data from the table
$config['per_page'] = 6;//number of data to be shown on single page
$config['first_link'] = 'First';
$config['last_link'] = 'Last';
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data["records2"] = $this->testimonial_model->get_all_testimonials($config["per_page"], $page);
$data['records7'] = $this->index_model->get_all_banners();
$data["links"] = $this->pagination->create_links();//create the link for pagination
$data['mainpage'] = "testimonial";
$this->load->view('templates/template',$data);
}
Model:
function get_all_testimonials($limit, $start)
{
$this->db->limit($limit, $start);
$this->db->select('T.*');
$this->db->from('testimonials AS T');
$this->db->where(array('T.status'=>1));
$q = $this->db->get();
if($q->num_rows()>0)
{
return $q->result();
}
else
{
return false;
}
}
View:
<div class="container">
<div class="row testimonialpage">
<div class="col-md-12 testimonialpage">
<div class="col-md-9 testimonials" >
<div class="testimonialpagetext">
</div>
<?php if(isset($records2) && is_array($records2)):?>
<?php foreach ($records2 as $r):?>
<div class="testimonial1">
<div class="testimonialtext1">
<?php echo $r->description;?>
<ul class="founders">
<li class="founder"><?php echo $r->client_name;?></li>
<li class="founder"><?php echo $r->founder;?></li>
</ul>
</div>
</div>
<?php endforeach ;endif;?>
<div class="pagination"><?php echo $links; ?></div>
</div>
</div>
</div>
For Ex:: Your url is www.example.com/controller/register when you get uri segment(2) means you will get (register). based on this you can identify that you are on the register page. now you can find the title for register page from your database.
Every time i build an application with Codeigniter, i use a Class MY_Controller that extends CI_Controller, inside application/core like bellow:
class MY_Controller extends CI_Controller {
protected $view_data;
function __construct() {
//......
}
}
Any controller inside application/controllers will extend the MY_Controller instead of CI_Controller.
Now in the constructor of MY_Controller you can do something like:
$page = $this->uri->segment(2); (2 or 3 or 4 etc, depends on your structure)
Load your model, execute your query and add the result in $this->view_data like:
$pageTitle = $this->your_model->getPageTitle($page);
$this->view_data['page_title'] = $pageTitle['page_title'];
Example of getPageTitle in your model:
public function getPageTitle($page) {
$qry = $this->db->select('page_title')
->from('pages')
->where('page', $page)
->get();
if ($qry->num_rows() > 0)
return $qry->row_array();
return false;
}
Watch out the sample names i gave, you should change those!
To load your view, pass the variable $this->view_data as parameter and in your view do something like
<title><?= $page_title ?></title>

Dynamic menu and Sub Menu in PHP Codeigniter

I am trying to create dynamic menu using PHP Codeigniter.
There are some Main Menu
Each Main Menu have some Sub_Menu Like, Categories ->Hardware, Software etc.
I somehow made it but there is an issue, the Main menu is showing correctly but the sub menu under main menu is repeating in each Main menu.
This is the image of the issue:
My View Code
<ul class="slimmenu">
<?php foreach($menus as $menu): ?>
<li>
<?php echo $menu -> Menu_Name;?>
<ul>
<?php foreach($submenus as $submenu): ?>
<li>
<?php echo $submenu -> Sub_Menu_Name;?>
</li>
<?php endforeach;?>
</ul>
</li>
<?php endforeach;?>
</ul>
My Controller Code
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MainSystem extends CI_Controller
{
function __construct() {
parent::__construct();
$this->load->model('menusys','ms');
}
function menu()
{
$this->data['menus'] = $this->ms->get_menu();
$this->data['submenus'] = $this->ms->get_submenu();
$this->load->view('index', $this->data);
}
function add_menu()
{
$data = array(
'Menu_Name' => $this->input->post('mname'),
'Menu_Link' => $this->input->post('mlink'),
);
$this->ms->adm($data);
}
function sub_menu()
{
$this->data['mmenu'] = $this->ms->get_menu();
$this->load->view('submenu', $this->data);
}
function add_submenu()
{
$data = array(
'Main_Menu_Name' => $this->input->post('mmname'),
'Sub_Menu_Name' => $this->input->post('mname'),
'Sub_Menu_Link' => $this->input->post('mlink'),
);
$this->ms->adsm($data);
}
}
?>
My Model Code
<?php
defined('BASEPATH') or exit('no direct script directy allowed');
/**
*
*/
class menusys extends CI_Model
{
public function __construct()
{
parent::__construct();
}
public function adm($data)
{
$this->db->set('Is_Active',0);
$this->db->insert('main_menu',$data);
$this->session->set_flashdata('msg', 'Meun has been added');
redirect('MainSystem/menu');
}
//sub-menu Section
public function get_menu()
{
//$this->db->where('Is_Active',1);
// $this->db->select('*');
// $this->db->from('main_menu');
// $this->db->join('sub_menu', 'main_menu.Menu_Name = sub_menu.Main_Menu_Name','inner');
// $query = $this->db->get();
// return $query->result();
//
$query=$this->db->get_where('main_menu',array('Is_Active'=>1));
return $query->result();
}
function get_submenu()
{
$this->db->where('main_menu.Menu_Name = sub_menu.Main_Menu_Name');
$this->db->select('*');
$this->db->from('sub_menu');
$this->db->join('main_menu', 'main_menu.Menu_Name = sub_menu.Main_Menu_Name','inner');
$query = $this->db->get();
return $query->result();
}
public function adsm($data)
{
$this->db->set('Is_Active',1);
$this->db->insert('sub_menu',$data);
$this->session->set_flashdata('msg', 'Meun has been added');
redirect('MainSystem/menu');
}
}
What I Want: I want that each Sub_Menu will show under his parent menu.
Any help will be appreciated.
UPDATE
This is sub-menu table image.
you need to format your menu array and loop it something like this
$menu = array(
'menu_name_1' => array(
'submenu1_1' => 'www.something.com',
'submenu1_2' => 'www.something.com',
),
'menu_name_2' => array(
'submenu2_1' => 'www.something.com',
'submenu2_2' => 'www.something.com',
)
);
foreach($menu as $menu_name => $submenu){
echo $menu_name.'<br>';
if (!empty($submenu)){
foreach($submenu as $submenu_name => $submenu_link){
echo ''.$submenu_name.'<br>';
}
}
}
You have array with menu names and submenu. First you loop menu name and check dose it has submenu, it if has, you loop submenu and make links.

CodeIgniter: Passing database array data to a template file

In my application I am trying to populate a sidebar menu list with rows from a database table. More specifically, I try to retrieve team name where the coach has the same user_id as the user that is logged in. I want to list the logged in coach's teams listed in a menu.
In my Model, I am using Active Record to get the desired query results:
public function get_team()
{
$this->db->select('teamname')->from('teams')->where('coaches', $this->session->userdata('user_id'));
$this->db->order_by('teamname', 'asc');
$query = $this->db->get();
if($query->num_rows() > 0)
{
foreach($query->result_array() as $row)
{
$data[] = $row;
}
return $data;
}
}
In the Controller, I am not sure how to go about in order to pass the array data to my view. In my index function, I do this:
public function index()
{
if (!$this->tank_auth->is_logged_in()) {
redirect('/auth/login/');
} else
{
$data['title'] = 'Team';
$data['main_content'] = 'team_v';
$data['username'] = $this->tank_auth->get_username();
$data['coach'] = $this->tank_auth->is_admin();
$this->load->vars($data);
$this->load->view('includes/template');
}
}
And in the relevant controller function, I try to send the data directly to the sidebar view, (which is included in the previously loaded template file):
public function get_team()
{
$data = array(
'result' => $this->team_m->get_team());
$this->load->view('includes/sidebar', $data);
}
The view code performs a standard foreach and looks like this:
<li>Teams</li>
<ul>
<?php /* if (empty($result)): */ ?>
<li>Create a team</li>
<?php /* else: */ ?>
<?php foreach ($result as $row): ?>
<li><?php echo $row['teamname'];?></li>
<?php endforeach; ?>
<?php /* endif; */ ?>
</ul>
<li>Messages</li>
<li>My profile</li>
<li>Logout</li>
Sending the $data array to the sidebar this way doesn't work. I have also tried to load all the views in the template manually and passing the data to the views, but to no avail. No matter how I pass it, it gives me the "Invalid argument supplied for foreach()" error, which AFAIK means that no data gets returned in the array.
However, if I do this in the controller function:
public function get_team()
{
$data = array(
'result' => $this->team_m->get_team());
$this->load->view('get_team_v', $data);
}
and make a get_team_v view with the exact same code in the sidebar view above, then the desired result is listed perfectly. I have also performed an affected_rows test and confirmed that the query part is good. What should I do to get the array data to be listed also in the templated sidebar view?
Solved, for anyone browsing.
Passing the arrays in the index method of the controller like below did it for me.
$data['result'] = $this->team_m->get_team_by_coach();
$this->load->vars($data);
And in the sidebar view like so:
<ul id="menu" class="nav nav-pills nav-stacked">
<li><span class="glyphicon glyphicon-list"></span>My Teams</li>
<ul id="submenu" class="nav">
<?php foreach ($result as $row): ?>
<?php echo '<li>' . $row['teamname'] . '</li>';?>
<?php endforeach;
if(count($result) <= 2)
{
echo '<li><a data-toggle="modal" id="create_team" data-backdrop="true" href="#create_team_modal" href="base_url(index.php/team/create_team)"><span class="glyphicon glyphicon-plus"></span>Create a team</a></li>';
}
?>
</ul>
<li><span class="glyphicon glyphicon-envelope"></span>Messages</li>
<li><span class="glyphicon glyphicon-user"></span></i>My Profile</li>
<li><span class="glyphicon glyphicon-log-out"></span>Logout</li>

Implementing pagination in codeigniter, can't get count

I am having difficulties implementing the codeigniter pagination class. I have created my model, view and controller for getting my news articles and data is echoed in the view successfully.
My problem is that when I attempt to implement pagination it seems like I am unable to get the correct count of fields in my database. Can somebody show me what I have done wrong?
The pagination links display perfectly, but the content echoed does not appear to be limited. How can I count the rows of the query?
Required classes for the pagination are autoloaded
Model:
class News_model extends CI_model {
function get_allNews()
{
$query = $this->db->get('news');
foreach ($query->result() as $row) {
$data[] = array(
'category' => $row->category,
'title' => strip_tags($row->title),
'intro' => strip_tags($row->intro),
'content' => truncate(strip_tags( $row->content),200),
'tags' => $row->tags
);
}
return $data;
}
Controller
// load pagination class
$config['base_url'] = base_url().'/news/index/';
$config['total_rows'] = $this->db->get('news')->num_rows();
$config['per_page'] = '5';
$config['full_tag_open'] = '<div id="pagination">';
$config['full_tag_close'] = '</div>';
$this->pagination->initialize($config);
$viewdata['allnews'] = $this->News_model->get_allNews($config['per_page'],$this->uri->segment(3));
View
<?php if (isset($allnews)): foreach ($allnews as $an): ?>
<?php echo heading($an['title'], 2); ?>
<?php echo $an['content']; ?>
<?php endforeach;
else: ?>
<h2>Unable to load data.</h2>
<?php endif; ?>
<?php echo $this->pagination->create_links(); ?>
In your controller, you're passing parameters to your get_allNews method, but your method doesn't make use of those parameters:
$viewdata['allnews'] = $this->News_model->get_allNews($config['per_page'],$this->uri->segment(3));
So you are getting all records, and expecting the limited result set. You need to change the beginning of your get_allNews method like this:
class News_model extends CI_model {
// make use of the parameters (with defaults)
function get_allNews($limit = 10, $offset = 0)
{
// add the limit method in the chain with the given parameters
$query = $this->db->limit($limit, $offset)->get('news');
// ... rest of method below

Codeigniter -> Edit Page

I am getting the following error when I try and access:
domain.co.nz/admin/editpage/home/
I get the following error:
PHP Fatal error: Call to a member function getCMSPage() on a non-object in controllers/home.php on line 22
The issue with this is that I cannot understand why it is being passed back into the main “home” controller - which is the main controller.
All of my models are loaded by default - http://cl.ly/2U1F3a2B0s2K0i3k3g13
Ideal Situation
What I am trying to do with this is load the content into a text area on for editing and when submit is clicked I would like it to go back to the same page with a message saying content updated.
Admin Template
<li><?php echo anchor('#','Edit Pages');?>
<?php if(is_array($cms_pages)): ?>
<ul>
<?php foreach($cms_pages as $page): ?>
<li><a >permalink?>"><?=$page->name?></a></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</li>
Page Model
function updatePage($data){
$data = array('content' => $content);
$this ->db->where('id',$id);
$this->db->update('pages',$data);
}
View:
<?php
//Setting form attributes
$formpageEdit = array('id' => 'pageEdit', 'name' => 'pageEdit');
$formInputTitle = array('id' => 'title', 'name' => 'title');
$formTextareaContent = array('id' => 'content', 'name' => 'content');
?>
<section id = "validation"><?php echo validation_errors();?></section>
<h4><?= $title ?> </h4>
<?php
echo form_open('admin/editpage/'.$page->permalink, $formpageEdit);
echo form_fieldset();
echo form_label ('Content', 'content');
echo form_textarea("content", $page['content']);
echo form_submit('submit','Submit');
echo form_fieldset_close();
echo form_close();
?>
Controller:
function index(){
if($this->session->userdata('logged_in')){
}else{
redirect('admin/home');
}
$page = $this->navigation_model->getCMSPage($this->uri->segment(3));
$data['cms_pages'] = $this->navigation_model->getCMSPages();
$data['title'] = $page->name;
$data['content'] = $this->load->view('admin/editpage', array('page' => $page, TRUE));
$this->load->view('admintemplate', $data);
}
I haven't really tested this yet but it should give you a good start. What you're asking is quite a bit of work to fully code out quickly.
This is the page_model model it's essentially what you posted with a few minor tweaks. Its best to use id's rather than strings. You may also want to do some htmlspecialchars or mysql hijack validation prior to passing these to your DB.
<?php
/**
* This is the Page_model model, this model handles the retrieval and modification of all pages.
*
**/
class Page_model extends CI_Model {
/**
* the getCMSPage function retrieves the data from the db given the ID that was passed via $id.
**/
function getCMSPage($id = NULL) {
$this->db->where('permalink', $permalink);
$query = $this->db->get('pages', 1);
#check to make sure row's were returned, if so continue, otherwise return false.
if ($query->num_rows() > 0){
#set the results into an array and return $row, should return $row['content'], and $row['id'];
#if you were editing more than one page this is where you would use a foreach($query)
$row = $query->result_array();
return $row;
}else{
return false;
}// END if ($query->num_rows() > 0)
}// END function getCMSPage()
}// END Page_model class
?>
This is the site controller and for sake of time i just echo'd your form_textarea straight from the edit function.. you shouldn't do this as it goes against MVC standards. You should create a view for that portion of the section.
<?php
/**
* This is the Site controller, primary controller for your site.
*
**/
class Site extends CI_Controller {
/**
* construct function, in our case we are going to load the Posts_model , you may not want to do this.
*
**/
function __construct()
{
parent::__construct();
#load Page_model, should be located in app/models/page_model.php
$this->load->model('Page_model');
}//END function __construct();
/**
* edit function, this function handles retrieval of the page from the URI, and the page's content for editing.
*
* This function uses $id which auto retrieves the page's ID from the uri. Your URL should look similiar to:
* http://yourdomain.com/site/edit/3/yourunecessaryinformationhere
* everything after the id is not really required but could help with SEO.
*
**/
function edit($id){
#retrieve the page's content in array form.
$page = $this->Page_model->getCMSPage($id);
echo form_textarea("content", $page['content']);
}
}//END Site Class
Keep in mind i wrote this up in 5-10 minutes so its rushed and not very well commented or even tested but itll give you a great head start. This only gives you an example of how to retrieve information from the DB and echo it into a textarea. You would still need to create another function within your page_model to insert/update the information and another snippet of code in your controller to pass the edited content to the model.
You can hit me up on AIM or twitter if you have more questions ThirdGenSup, twitter is #gorelative
// this line
$data['content'] = $this->load->view('admin/editpage', $data);
// needs to be
$data['content'] = $this->load->view('admin/editpage', array('page' => $page, TRUE);

Categories