What happens to $data when it is passed to the view? |
Could someone help me get my head around what happens when you pass $data to the view?
For example, in the controller I have... PHP Code: $data['getMessages'] = $this->test_model->get_messages(); Then I pass the $data array to the view... PHP Code: $this->load->view('/test/index', $data); What happens to $data for it to be accessible with $getMessages in the view? Thanks.
In the view, it is extracted from the array, and turns to the variable $getMessages.
Then, you should access your data like this: $getMessages[0]->messages
Hi,
probably you in get_messages(), you are returning object form rather than and array form. Check documentation and look into difference for result() and result_array() http://www.codeigniter.com/user_guide/da...sults.html I hope this helps.
Hi!
You can do this: $return = array(); $data = array(); $data['getMessages'] = $this->test_model->get_messages(); $data['foo'] = 'bar'; $return['data'] = $data; $this->load->view('/test/index', $return); Now in view you can access to $data['getMessages'] or $data['foo'] (04-29-2015, 08:14 AM)n2fole00 Wrote: Could someone help me get my head around what happens when you pass $data to the view? When you pass data to the view, every item in the array you pass becomes a variable so you must access to it from the view like this. $getMessages->message
Eventually, the $data is passed (along with variables set through other methods) to extract(), which imports the values to variables named for the associated keys in the array and exposes them for use in your view.
$data['getMessages'] = $this->test_model->get_messages();
becomes $getMessages in the view. As mwhitney mentioned, CI runs extract() on the array passed to the viewfile. http://www.codeigniter.com/user_guide/ge...o-the-view
just as an fyi you can also use $this->something to pass data to the view.
i think in general its better to pass it explicitly with $data but there are times when $this-> gives you more flexibility. PHP Code: // in controller also works great for development or error messages because you set it in any controller / model method and it will show up in the view(s) that are called. PHP Code: // if the greeting is not returned, create a developer message |
Welcome Guest, Not a member yet? Register Sign In |