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>
Related
I'm creating a project where in I want to verify if there is a data that has been inserted in a table by a certain user and display it if there's any. I'm fairly new to CodeIgniter and I'm unsure of how to display all the lists that has been by a certain user if it is logged in.
This is what I have in my model so far:
public function get_all_lists($user_id){
$this->db->where('list_creator_id', $user_id);
$query = $this->db->get('lists');
return $query->result();
}
This is what I have on my view:
<li class="list-group-item">
<a href="<?php echo base_url();?>project_controllers/lists/create" class="btn btn-success pull-right">
Create a List
</a>
<h3 align="center">
<a href="<?php echo base_url();?>project_controllers/lists/display/<?php echo $list->id;?>">
<?php echo $list->list_name; ?>
</a>
</h3>
</li>
<?php endforeach; ?>
And this is what I have on my controller:
public function index(){
$user_id = $this->session->userdata('user_id');
$this->load->model('project_models/lists_model');
$data['lists'] = $this->lists_model->get_all_lists($user_id);
$data['main_view'] = "project_views/lists/index";
$this->load->view('project_views/layouts/main', $data);
}
My goal here is to display all the lists that has been created by a certain user if it is logged in. If the user has been logged in and has not created any list, I want a message that says, "You don't have created any lists yet".
Use num_rows() to return either the object or false.
public function get_all_lists($user_id){
$this->db->where('list_creator_id', $user_id);
$query = $this->db->get('lists');
if ($query->num_rows() > 0) {
return $query->result();
}
return false;
}
Usage:
if ($lists) {
foreach(...) {
}
} else {
echo 'no rows';
}
I'm trying to learn Laravel while writing some common features. Now what I'm trying to make is when I click on main category link to open new page and display all sub-categories assigned to this category. Sounds pretty simple but I can't display them.
This is what I have in my Category Model
public function parent()
{
return $this->belongsTo('App\Category', 'parent_id');
}
public function children()
{
return $this->hasMany('App\Category', 'parent_id');
}
And in controller
public function categoryListing( $category_id )
{
$categories = Category::with('children')->get();
$category = Category::find($category_id);
if($category->parent_id == 0) {
$ids = Category::select('id')->where('parent_id', '!=',0)->get();
$array = array();
foreach ($ids as $id) {
$array[] = (int) $id->id;
}
} else {
$items = Item::where('category_id' ,$category_id)->paginate(5);
}
return view('category_list', compact('categories','items'));
}
The idea here is to display Main Category and all sub-categories (childs) of this main category.
And this is the loop on the page
#foreach($categories as $category)
<a href="{!!route('list',array($category->id))!!}">
<span><strong>{!!$category->title!!}</strong> ({!! $category->itemCount!!})</span>
</a>
<ul class="list-group">
#foreach($category as $subcategory)
{!!$subcategory->title!!}
<span class="badge badge-primary badge-pill">{!! $subcategory->itemCount !!}</span>
</li>
#endforeach
</ul>
#endforeach
Current error is
Trying to get property of non-object
on the inside foreach.
Just try this is 'cleaner'.. if it works, start adding your links and other content so you will know what does not work.
#foreach($categories as $category)
<span><strong>{!!$category->title!!}</strong></span>
<ul class="list-group">
#foreach($category as $subcategory)
<li>{!!$subcategory->title!!}</li>
#endforeach
</ul>
#endforeach
Make sure the variables you try to print exist in each object.
You can try to dd($categories); in your controller before the return view('category_list', compact('categories','items')); statement to see whats inside $categories
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>
This question already has an answer here:
Database driven menu that can be loaded in view
(1 answer)
Closed 5 years ago.
So,I have a the navbar in my home page where all the module name gets listed from the database. Instead of re-writing the whole code to list module name in all page I decided to use blade's #yeild() functionality.
This is my home page Controller where I get all the module names and pass it to the homepage view like so
public function index()
{
$data = Module::get();
return view("BaseView.home")->with('data',$data);
}
This is my homepage view where I display all the modules and it's respective name in the navbar like so
<ul class="navbar-nav">
#foreach($data as $modules)
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
{{ $modules->module_name) }}<i class="plusMinus" aria-hidden="true"></i>
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
#foreach($modules->module_categories as $category)
<?php
$getModuleNameToLowerCase = strtolower($modules->module_name);
$getCategoryNameToLowerCase = preg_replace('/\s+/', '_', strtolower($category->categories_name));
?>
<a class="dropdown-item" href="#">{{ $category->categories_name }}</a>
#endforeach
</div>
</li>
#endforeach
</ul>
<div class="container-fluid">
#yield('mainBody')
</div>
Now When I extend this in another view like so
#extends('BaseView.home')
I get Undefined variable: data.
Can someone help me/guide me on how to solve this issue?
In you controller, you need to pass modules to each view, because view does not keep the values after new request. For each request there must be modules ($data).
Remember, the data passed to master blade using one controller method will not work for another controller method, because every time each new request need all values of those variables again that are used in master and child blades.
Controller
//..............
//.................
public function index()
{
$data['modules'] = Module::get();
//$data['other_data'] = User::get(); //To get other data and pass to your view
return view("BaseView.home")->with('data',$data);
}
public function profilePage()
{
$data['modules'] = Module::get();
//$data['profile_detail'] = Profile::get(); //To get other data and pass to your view
return view("BaseView.home")->with('data',$data);
}
//Something like this
But writing $data['modules'] = Module::get(); for each controller method, you can write it inside your constructor of the your controller. This will be for all methods (Requests) .
public function __construct(){
$data['modules'] = Module::get();
}
public function index()
{
//$data['other_data'] = User::get(); //To get other data and pass to your view
return view("BaseView.home")->with('data',$data);
}
//................
//.................
And view:
<ul class="navbar-nav">
<?php
if(isset($data['modules'])&&count($data['modules'])>0){
?>
#foreach($data['modules'] as $modules)
.............
..............
#endforeach
<?php
}
else{
echo "Modules are not available";
}
?>
</ul>
<div class="container-fluid">
#yield('mainBody')
</div>
The above is for your error message, But if you want that modules to be available anywhere then you can use session or creating helper
Instead of passing data on every view, use Providers boot method which triggers before loading any view and pass your default data on every view. simple.
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)