Welcome Guest, Not a member yet? Register   Sign In
Dynamic sidebar routing issue
#1

[eluser]Unknown[/eluser]
Hi,

Just starting out with CI. I've followed the initial tutorial and started adapting it to my own purposes.

As well as a header and footer I wanted to make a sidebar that is populated from categories in a database.

So I made a model - /application/models/sidebar_model.php
Code:
<?php
class Sidebar_model extends CI_Model {

public function __construct()
{
  $this->load->database();
}

public function get_cats()
{
  
   $query = $this->db->get('categories');
   return $query->result_array();
}

}

A controller - /application/controllers/sidebar.php
Code:
<?php
class Sidebar extends CI_Controller {

public function __construct()
{
  parent::__construct();
  $this->load->model('sidebar_model');
}

public function index()
{
  $data['categories'] = $this->sidebar_model->get_cats();
  
  $this->load->view('sidebar/index', $data);
}


}

and a view - /application/views/sidebar/index.php
Code:
<div id="sidebar">
&lt;?php foreach ($categories as $category): ?&gt;

    <p>&lt;?php echo $category['name'] ?&gt;</p>
    
&lt;?php endforeach ?&gt;
</div>

I then added this line as my first route -
Code:
$route['sidebar'] = 'sidebar';

Then attempted to call the sidebar from my main 'pages.php' controller, like so
Code:
$this->load->view('templates/header', $data);
  $this->load->view('pages/'.$page, $data);
  $this->load->view('sidebar/index', $data);
  $this->load->view('templates/footer', $data);

This results in PHP errors being thrown up in the sidebar area -

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: categories

Filename: sidebar/index.php

Line Number: 2

But - if I go directly to http://development_environment/index.php/sidebar then I see the list of categories that I'm trying to display.

I'm guessing this is a routing issue, or am I missing something else?

Thanks in advance....
#2

[eluser]CroNiX[/eluser]
Why do you need a route for something that is only used internally? I'm guessing a user wouldn't be accessing the sidebar directly via the url - it's accessed only internally by your app. So why do you need a route here?
#3

[eluser]Unknown[/eluser]
I guess it doesn't! Though having the route set up does allow me to confirm that the sidebar works on its own.

So, I removed the route but am still getting the same php errors. Can anyone point me to where I've gone wrong?

Thanks.
#4

[eluser]CroNiX[/eluser]
Code:
$this->load->view('sidebar/index', $data);
implies you have a view file:
/application/views/sidebar/index.php, which the error indicates does not exist.

perhaps the view should be named
/application/views/sidebar_index.php

I wouldn't name any file "index.php" unless it is actually the CI bootstrap file.





Theme © iAndrew 2016 - Forum software by © MyBB