Welcome Guest, Not a member yet? Register   Sign In
How to set a global data to all views in a controller
#1

[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.
#2

[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);
}
}
#3

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

or

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

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

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

[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.
#6

[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




Theme © iAndrew 2016 - Forum software by © MyBB