CodeIgniter Forums
Passing object to 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: Passing object to views (/showthread.php?tid=6903)



Passing object to views - El Forum - 03-16-2008

[eluser]Unknown[/eluser]
Hi, a newbie question again. In the user guide it says that you can load a view passing an object variable to it. How do I access that object in the view?

Suppose I have the following code in my model "mymodel":
Code:
...
function get_record() {
   $cond = ...  // some selection criteria
   $query = $this->db->get_where('mytable', $cond);
   return $query;
}

And in my controller "mycontroller":
Code:
...
function retrieve() {
   $results = $this->mymodel->get_record();
   $this->load->view("myview", $results);
}

How should I access the query results in my view "myview"? Am I doing it right?
Thank you for your help!!


Passing object to views - El Forum - 03-17-2008

[eluser]webthink[/eluser]
In your example you would simply use the $results var.

so in your view.
Code:
<?
foreach ($results->result() as $row)
{
  echo $row->field;
}
?>

EDIT: Sorry hadn't noticed that you didn't pass an associative array to your view... If your controller looked somthing like this


Code:
...
function retrieve() {
   $data['results'] = $this->mymodel->get_record();
   $this->load->view("myview", $data);
}

Then the view code above would work.


Passing object to views - El Forum - 03-17-2008

[eluser]xwero[/eluser]
[quote author="rtpub" date="1205745297"]
Code:
...
function get_record() {
   $cond = ...  // some selection criteria
   $query = $this->db->get_where('mytable', $cond);
   return $query;
}
[/quote]
A hint : use as little variables as possible because they use memory
Code:
...
function get_record() {
   $cond = ...  // some selection criteria
   return $this->db->get_where('mytable', $cond);
}