Saturday, February 23, 2013

Templating with CI

Let’s see how to templating with CI.
  • Create Template : Create a file template.php in application/views with the below content.
  • Changing default Controller : By default, the controller will be welcome. If you want, you can change the configuration in application/config/routes.php file. Change the default_controller to your custom one (Note: Dont include extension).
  • Create Controller : Create the controller(If you have changed the default controller or exisitng one). Change the index function with the following .
  • Create View : Create header.php, login.php and footer.php in application/views.
By default, the Login page will be opened in place of content. index is the default function called in the controller. As we mentioned the above lines of code in default contoller’s default function. So, when we open the page. we will login page with header and footer.
  • Example : the contents of the three files are as follows
This is header part
This is footer part
<?=form_open(‘welcome/login’); ?>
Login Name<br />
<?=form_input(‘username’,”,’class=text’)?><br />
Password<br />
<?=form_password(‘password’,”,’class=text’)?><br />
<input type=”submit” name=”login” value=”Login” class=”button” />
<?=form_close(); ?>
The first line in login.php says, when the form is submitted, the action goes to login function in welcome controller. Notation is controller/function_name. If we dont specify the function, by default index function will be called.
In the function login, do the login validation and re-direct based on the validation. For example
public function login() {
$user_name = $this->input->post(‘username’);
 $user_pass = $this->input->post(‘password’);
if($user_name == $user_pass ) {
$data['content'] = ‘home’;
else  {
For login authentication, we can use models as well. Create the file in application/model and call in the controller.
User.php in application/model
$user = new User();
$user->username = $user_name;
$user->password = $user_pass;
$status = $user->login();
Instead of if condition in login function, use the status variable to redirect to the respective page. So, based on the login, it will redirect to login or home page.