Passing a variable from MY_Controller to a view Passing a variable from MY_Controller to a view codeigniter codeigniter

Passing a variable from MY_Controller to a view


You have a couple of options

You can use a $this->data property on your MY_Controller and then make sure you pass $this->data to all your views

// MY_Controllerpublic $data;public function __construct(){    if($this->is_logged_in())     {        $this->username = $this->session->userdata('username');        $this->data['login_prompt'] = "Hi, " . $this->username . " " . anchor("account/logout", "Logout");    }}

And then in our controller..

// An example controller. By extending MY_Controller // We have the data property availableUcpController extends MY_Controller{    public function __construct()    {        parent::__construct();    }    public function index()    {        $this->data['Some extra variable'] = 'Foo';        // Notice we are giving $this->data rather than $data...        // this means we will have our login prompt included        // as it is set by the parent class        $this->template->build("ucp/ucp_view", $this->data);    }}

Alternatively you can set up a global array in MY_Controller and then use the load->vars method to make the array available to all your views

// MY_Controllerpublic $global_data;public function __construct(){    if($this->is_logged_in())     {        $this->username = $this->session->userdata('username');        $this->global_data['login_prompt'] = "Hi, " . $this->username . " " . anchor("account/logout", "Logout");        $this->load->vars($this->global_data);    }}


Try switching $data['login_prompt'] to $login_prompt in your view.

The error message 'undefined index' is referring to 'login_prompt' not being an index in the associative array $data. Code igniter breaks up that array you pass to $this->load->view(). Similar to how extract() works (php docs, ci docs).