Welcome Guest, Not a member yet? Register   Sign In
Use variables from controller in views
#1

[eluser]woracal[/eluser]
Maybe a stupid question. How do I use variables from a controller in a view? Appreciate any help. Thanks!
#2

[eluser]Glen Swinfield[/eluser]
When you load the view, pass your vars in an array:

Code:
$to_controller['variable_one'];
$to_controller['variable_two'];
$to_controller['variable_three'];
$this->load->view('myview', $to_controller);

Then in your view use $variable_one etc to access the variables.

EDIT: should have named that variable $to_view or $from_controller for clarity - I don't know what I was thinking - it will still work though..
#3

[eluser]Iksander[/eluser]
Reading the documentation should help a great deal as well - it is very clear and has good examples.
#4

[eluser]amey[/eluser]
Hi,

Passing variables from controller to view is not working for me. When I try to print the variables in the view, it throws up a notice "undefined variables"

Controller:
$this->template->load("view", $variable);

View(view.php):
&lt;?php echo "<pre>"; print_r($variable); echo "</pre>"; ?&gt;

Any help would be appreciated.

Thanks.

-Amey
#5

[eluser]pistolPete[/eluser]
Read the User Guide!
Quote:Data is passed from the controller to the view by way of an array or an object in the second parameter of the view loading function.
#6

[eluser]amey[/eluser]
Hi,

Thank you for the reply.

In the example above $variable is indeed an array.

I have used this before and it used to work.

It has suddenly stopped working.

Could there be any known reason for this?

Thanks again for your help.

-Amey.
#7

[eluser]pistolPete[/eluser]
If it is an array in you controller, you do not access it as an array in your view!

Code:
$data = array(
               'first' => 'abc',
               'second' => 'xyz');

$this->load->view('view', $data);

In your view, you now access the variables $first and $second, which are the keys oft the assoc array $data.
Code:
echo $first.' - '.$second;




Theme © iAndrew 2016 - Forum software by © MyBB