Sunday, May 10, 2009

Sending array to a view file [ Step 5 ]

Lets go back to the controller, at this point we done - pass two simple strings to a view file.
I like to send a different data type to view file, so I create a new index call todo and I like to send an array to a view file. Ok I got array with three elements in side index call todo.
class Blog extends Controller
{
function Index()
{
data['title'] = "My blog title";
data['heaading'] = "My blog heading";
data['todo'] = array( 'clean house','eat lunch','call man');
this->load->view('blog_view', $data);
}
}
I create an order list and I use for each loop to do this , and you know that I'am using an alternative PHP syntax using a column instead of an opening brace and like wise instead of an opening brace I use an endforeach construct now I copy an element to list element.
<html>
<head>
<title> <?=$title; ?> </title>
</head>
<body>
<h1> <?=$heading ; ?> </h1>
<ol>
<?php foreach($todo as $item): ?>
<li> <?= $item ?> </li>
<?php endforeach; ?>
</ol>
</body>
</html>
So I reload a page you know see a todo list , so I can pass arrays to view files multidimensional array,objects, it's really use data type you want to work with. One thing before I'am going to the controller and create a constructor, in PHP a constructor is a simply function that named identically to the class, in PHP5 it's a little a bit syntax if you use a local constructor you need to be override constructor that contain parent class the side effect is it will break you application.
class Blog extends Controller
{
function Blog()
{

}
function Index()
{
data['title'] = "My blog title";
data['heaading'] = "My blog heading";
data['todo'] = array( 'clean house', 'eat lunch' , 'call man');
this->load->view ('blog_view', $data );
}

}
If I reload a page you see that know I get an error message
In line number 16.
Fatal error : Call to a member function view()  on non-object  in blog.php line 16.
In order to fix this we need to explicitly call the constructor in the parent class.
With that single line of code I reestablish that relationship
class Blog extends Controller
{
function Blog()
{
parent::controller();
}
function Index()
{
data['title'] = "My blog title";
data['heaading'] = "My blog heading";
data['todo'] = array( 'clean house', 'eat lunch' , 'call man');
this->load->view ('blog_view', $data );
}
}
and I can reload a page and that my application is working again.
So remember any time you use a constructor to explicitly call your parent controller class.

That's all folks

We created a controller , made a view file , generate some dynamic information that we pass to view file and this should see how easy is CodeIgniter to use. This is your first look in a model view controller approach I'll think you see very nice separation in your application logic and
your display element, in later tutorials we will expand this information.
You can see video tutorial
here

No comments:

Post a Comment