CodeIgniter Forums
Variable from Controller not working in Views - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Variable from Controller not working in Views (/showthread.php?tid=53976)



Variable from Controller not working in Views - El Forum - 08-16-2012

[eluser]Kraig[/eluser]
Why is the variable test_var not working in the view like the guide shows? Variable is created at the end.
Controller:
Code:
class Members_area extends CI_Controller {

function index()
{
  $is_logged_in = $this->loggedin->loggedin();
  if(!$is_logged_in)
  {
   $data['main_content'] = 'home';
   $this->load->view('includes/template2', $data);
  }
  else
  {
   $data['main_content'] = 'members_area';
   $this->load->view('includes/template2', $data);
  }
  
  // Grabbing all the files associated with the current user
  $this->load->model("upload_model");
  $q = $this->upload_model->get_files();
  $data['test_var'] = 'Test'; // Trying to use this variable in the views file

}

}

The View File:
Code:
<li>&lt;?php echo $test_var;?&gt;</li>

I get undefined variable as an error


Variable from Controller not working in Views - El Forum - 08-16-2012

[eluser]xtremer360[/eluser]
That's because you have to define the data array key before you send the data array to the view file. So what I would suggest is sense both the key values are the same that are inside the if and else statements I suggest you take it out of it and move it to the bottom that way you only have to have that line once that way those bottom three lines will all work for you.


Variable from Controller not working in Views - El Forum - 08-16-2012

[eluser]Kraig[/eluser]
Not sure what you mean...


Variable from Controller not working in Views - El Forum - 08-16-2012

[eluser]xtremer360[/eluser]
Try this:

Code:
class Members_area extends CI_Controller {

function index()
{
  $is_logged_in = $this->loggedin->loggedin();
  if(!$is_logged_in)
  {
   $data['main_content'] = 'home';
  }
  else
  {
   $data['main_content'] = 'members_area';
  }
  
  // Grabbing all the files associated with the current user
  $this->load->model("upload_model");
  $q = $this->upload_model->get_files();
  $data['test_var'] = 'Test'; // Trying to use this variable in the views file
  $this->load->view('includes/template2', $data);
}

}



Variable from Controller not working in Views - El Forum - 08-16-2012

[eluser]Kraig[/eluser]
Thanks!!


Variable from Controller not working in Views - El Forum - 08-16-2012

[eluser]Kraig[/eluser]
Had to change it slightly, but it worked!