CodeIgniter Forums

Full Version: How to set a global data to all views in a controller
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]Jeyakumar[/eluser]
class User extends Controller {

function User()
{
parent::Controller();
$data['page'] = "User";
}

function index(){
$data['title'] = "Welcome Page";
$this-load->view('home_view', $data);
}
}

While loading the home view, the $page variable is not available. It through the error as undefined.

Any possibilities to load a variable to all the views based on the controller.

El Forum

[eluser]whitey5759[/eluser]
You would need to declare a class wide scope variable (well ok we all know in PHP you don't have to declare it, but it's good practice/good coding to do so) in the Controller in order for it to be accessible in all methods in the Controller. So, following on from your example:

class User extends Controller {

var $data;

function User()
{
parent::Controller();
$this->data["page"] = “User”;
}

function index(){
$this->data["title"] = “Welcome Page”;
$this-load->view(‘home_view’, $this->data);
}
}

El Forum

[eluser]Colin Williams[/eluser]
1.) Use $this->data, not simply $data.

or

2.) Use $this->load->vars()

El Forum

[eluser]xwero[/eluser]
Yes using the load->vars method
Code:
class User extends Controller {

  function User()
  {
      parent::Controller();
      $this->load->vars(array(‘page’=>“User”));
  }
// ...

El Forum

[eluser]Colin Williams[/eluser]
I'd lean the way xwero does too. $this->load->vars() is an oft-forgotten function, but it is so essential.

El Forum

[eluser]Dam1an[/eluser]
I personally prefer the $this->data approach, as I have a custom super controller which needs access to the data as well (and $data is declared there) and it just seems so much easier that way Smile