Sunday, 15 November 2015

How to create login and logout.

View:
<center> <?php echo $this->session->flashdata('error_message_name');?>  </center>
<form class="form col-md-12 center-block" action="<?php echo base_url();?>admin/login/validate_credentails" method="post" name="login-form">
          <div class="form-group">
            <input type="text" id="username" name="username" class="form-control" placeholder="User Name"  autofocus="autofocus" required="required">
          </div>
          <div class="form-group">
            <input type="password" id="password" name="password" class="form-control" placeholder="Password"  required="required">
          </div>
          <div class="form-group">
            <input type="submit" value="Sign In" name="submit" class="btn btn-primary btn-lg btn-block">
            <span class="pull-right"> <?php echo anchor('admin/register','Register');?></span> </div>
        </form>
********************************************************************************

Controller:

  public function lcheck() {

        $this->load->database();     

        if ($this->session->userdata('is_login')) {
            redirect('contact');
        } else {
              $user = $_POST['username'];
            $password = $_POST['password'];
           
                $this->db->select('*');
                $this->db->from('tbl_users');
                $this->db->where('user_name',$user);
                $this->db->where('user_password',$password);                               
                $val=$this->db->get();
               
                if ($val->num_rows()>0) {
                    foreach ($val->result_array() as $recs => $res) {
                        $this->session->set_userdata(array(
                            'id' => $res['user_id'],
                            'username' => $res['user_name'],                           
                            'useremail' => $res['user_email'],                                                       
                            'is_login' => true)
                        );
                    }
                    redirect('dashboard');
                   
                } else {   
            $this->session->set_flashdata('success_message', 'Error in username or password.');              
            redirect('login');
                }
         
        }
 }

  public function logout() {
        $this->session->unset_userdata('user_id');
        $this->session->unset_userdata('user_name');
        $this->session->unset_userdata('is_admin_login');  
        $this->session->sess_destroy();
        $this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate, no-transform, max-age=0, post-check=0, pre-check=0");
        $this->output->set_header("Pragma: no-cache");
        redirect('login', 'refresh');
    }

How to create pagination, sorting and searching using dataTables

Add 2 files in you header file.

<link href="<?php echo base_url('admin/css/jquery.dataTables.css');?>" rel="stylesheet" type="text/css">
<script src="<?php echo base_url('admin/js/jquery.dataTables.js'); ?>"></script>

Write below line in bottom of file.

 <!-- Table -->
        <table class="table" id="users_form">
          <thead>
            <tr>
              <th>#</th>
              <th>Event Title</th>
              <th>Event Start Date</th>
              <th>Event End Date</th>             
              <th id="action">Action</th>
            </tr>
          </thead>
          <?php 
         
          for ($i=0;$i<count($show);$i++) { ?>
          <tr>
            <td><?php echo $i+1; ?></td>
            <td><?php echo $show[$i]['event_title']; ?></td>
            <td><?php echo $show[$i]['event_startDay']; ?></td>
            <td><?php echo $show[$i]['event_endDay']; ?></td>           
            <td>
            <a href="<?php echo base_url(); ?>admin/event/edit_cms/<?php echo $show[$i]['event_id']; ?>">Veiw</a> |
             <a href="<?php echo base_url(); ?>admin/event/edit_cms/<?php echo $show[$i]['event_id']; ?>">Edit</a> | <a href="<?php echo base_url(); ?>admin/event/delete_users/<?php echo $show[$i]['event_id']; ?>">Delete</a></td>
          </tr>
          <?php } ?>
        </table>

<script>$(document).ready(function() {
  $('#users_form').dataTable();
});
</script>

Special note: How to remove sorting on any field. Add below lines.

<style> #action { background-image: none; pointer-events:none; } </style>

How to use datetime picker.

Add 2 files in your header and footer files.


<link href="<?php echo base_url('admin/css/jquery.datetimepicker.css');?>" rel="stylesheet" type="text/css">
 <script src="<?php echo base_url('admin/js/jquery.datetimepicker.js'); ?>"></script>

Write the script in your footer or in the page where you want.
<script>/*
    window.onerror = function(errorMsg) {
        $('#console').html($('#console').html()+'<br>'+errorMsg)
    }*/
    $('#datetimepicker1').datetimepicker({
    dayOfWeekStart : 1,
    lang:'en',
    disabledDates:['1986/01/08','1986/01/09','1986/01/10'],
   
    });
    $('#datetimepicker2').datetimepicker({
    dayOfWeekStart : 1,
    lang:'en',
    disabledDates:['1986/01/08','1986/01/09','1986/01/10'],
    });
   
    $('#datetimepicker_dark').datetimepicker({theme:'dark'})
    </script>

*********************************************************************************
Add below lines for datetime picker.
<input type="text" name="event_start_date" id="datetimepicker1" value="" class="form-control" data-parsley-required-message="Start Date cannot be blank" required>

 <input type="text" name="event_end_date" id="datetimepicker2" value="" class="form-control" data-parsley-required-message="End Date cannot be blank" required>

How to use parsley form validation in codeigniter

Add 2 files in your header file. You can download from http://parsleyjs.org/.

<link href="<?php echo base_url('admin/css/parsley.css');?>" rel="stylesheet" type="text/css">
<script src="<?php echo base_url('admin/js/parsley.js'); ?>"></script>

When you create a form add (data-parsley-validate data-toggle="validator") as shown in below example.

<form role="form" action="<?php echo base_url();?>admin/add_users/add" method="post" name="add-users" id="add-users"  data-parsley-validate data-toggle="validator">

For custom message in parsley you can write as shown in below example.

 <input class="form-control" name="users_fname" id="users_fname" required="required"         data-parsley-required-message="First name cannot be blank">

More example can be found here. http://parsleyjs.org/doc/examples.html

How to create a contact form

This is view part:
<?php echo $this->session->flashdata('message');?>
      <form action="<?php echo base_url();?>contact" id="form1" name="form1" method="post" enctype="multipart/form-data">
        <div class="row">
          <div class="col-md-6 col-sm-6">
            <div class="form-group"> <span style="float:left;">&nbsp;
              <?=form_error('full_name');?>
              </span><br />
              <input type="text" name="full_name" id="full_name" class="form-control" value="<?=set_value('full_name');?>"   placeholder="Full Name"/>
            </div>
          </div>
          <div class="col-md-6 col-sm-6">
            <div class="form-group"> <span style="float:left;">&nbsp;
              <?=form_error('email');?>
              </span><br />
              <input type="text" name="email" id="email" class="form-control" value="<?=set_value('email');?>"   placeholder="Email address">
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-md-12 col-sm-12">
            <div class="form-group"> <span style="float:left;">&nbsp;
              <?=form_error('message');?>
              </span><br />
              <textarea name="message" id="message"  class="form-control" rows="7" placeholder="Message"><?=set_value('message');?>
</textarea>
            </div>
            <div class="form-group">
              <input name="submit" type="submit" class="btn btn-primary" value="Submit Request"  />
            </div>
          </div>
        </div>
      </form>
*******************************************************************************
This is controller part:
 <?php defined('BASEPATH') OR exit('No direct script access allowed');

class Contact extends CI_Controller {
    function __construct() {
        parent::__construct();
        //Write the below code when you have not autoload below settings.
              
        //$this->load->helper(array('form', 'url', 'html'));
        //$this->load->library('form_validation');
      
        //If you have set in autoload then don't write below 2 commented lines.
      
        //If you want custom error message then write the below lines.
        $this->form_validation->set_message('alpha','Invalid Name');
        $this->form_validation->set_message('valid_email', 'Invalid Email Address');      
        $this->form_validation->set_message('required', 'Require');  
    }
  
    public function index()
    {
        if(!file_exists('application/views/contact.php')) { show_404(); }
        $data['title'] = "Contact us";
        $this->load->view('templates/header',$data);
        $this->load->view('templates/navigation');
        $this->load->view('contact');
        $this->load->view('templates/footer');
    }  
  
    public function contact(){
         $this->form_validation->set_error_delimiters('<div class="error">', '</div>');

         $this->form_validation->set_rules('full_name', 'Full Name', 'trim|required|alpha|min_length[3]|max_length[15]');
         $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');        
         $this->form_validation->set_rules('message', 'Message', 'required');
        
         if ($this->form_validation->run() == FALSE)
            {
                $data['title'] = "Contact us";
                $this->load->view('templates/header',$data);
                $this->load->view('templates/navigation');
                $this->load->view('contact');
                $this->load->view('templates/footer');
            }           
        else
            {
                $this->load->model('contactform_model');
                $data['query'] = $this->contactform_model->form_insert();
            }  
    }
}


******************************************************************************* 
This is model part:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Contactform_model extends CI_Model
{
    public function __construct()
    {
        parent::__construct();       
           
    }
   
    function form_insert(){
       
        $fullname = $this->input->post('full_name');
        $email = $this->input->post('email');   
        $message = $this->input->post('message');   
       
        $sql = "INSERT INTO tbl_contact(contact_fullname,contact_email,contact_message)
        VALUES ('$fullname','$email','$message')";               
       
        $result = $this->db->query($sql);   
        if($this->db->affected_rows()>0){
            $this->session->set_flashdata('message', '   
            <div class="alert alert-success alert-dismissible" role="alert">
    <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>Successfully added</div>'); 
           redirect('contact','refresh');  
       }
       else{
           $this->session->set_flashdata('message', '          
           <div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
Cannot be added</div>          
           ');
           redirect('contact','refresh');  
       }
    }
}   

How to remove index.php from url

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond $1 !^(index\.php|(.*)\.swf|forums|images|css|fonts|downloads|jquery|js|robots\.txt|favicon\.ico)

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php/$1 [L]

RewriteRule ^(admin/)$ admin/login.php?/$1 [L]
RewriteRule ^([A-Za-z0-9-]+)/?$ index.php?id=$1 [L]
</IfModule>