Minggu, 02 Juni 2013

Multiple Event Calendar with Codeigniter

Well, after long time didn't post about sharing. Now i'm sharing about multiple event calendar with Codeigniter framework that named "Evencal" (sorry for other code that have same name.. ^_^ ).


This is an update from my event calendar. Evencal using :
  1. Codeigniter 2.1.3 update Codeigniter 3
  2. jQuery 1.7.2
  3. jQuery Colorbox
  4. CSS Notification Boxes

This is screenshoot :

At first, create code SQL for database Evencal. This application using MYSQL Database :
CREATE TABLE IF NOT EXISTS `events` (
  `event_date` date NOT NULL,
  `total_events` int(50) NOT NULL DEFAULT '0',
  PRIMARY KEY (`event_date`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `event_detail` (
  `idevent` int(11) NOT NULL AUTO_INCREMENT,
  `event_date` date NOT NULL,
  `event_time` time NOT NULL,
  `event` varchar(200) NOT NULL,
  PRIMARY KEY (`idevent`),
  KEY `event_date` (`event_date`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=34 ;

ALTER TABLE `event_detail`
  ADD CONSTRAINT `event_detail_ibfk_1` FOREIGN KEY (`event_date`) REFERENCES `events` (`event_date`);

and then create controller evencal.php
class Evencal extends CI_Controller {
 function __construct(){
  parent::__construct();
  $this->load->model('evencal_model', 'evencal');
  $this->load->library('calendar', $this->_setting());
 }
 
 function index($year = null, $month = null, $day = null){
  $year  = (empty($year) || !is_numeric($year))?  date('Y') :  $year;
  $month = (is_numeric($month) &&  $month > 0 && $month < 13)? $month : date('m');
  $day   = (is_numeric($day) &&  $day > 0 && $day < 31)?  $day : date('d');
  
  $date      = $this->evencal->getDateEvent($year, $month);
  $cur_event = $this->evencal->getEvent($year, $month, $day);
  $data      = array(
      'notes' => $this->calendar->generate($year, $month, $date),
      'year'  => $year, 
      'mon'   => $month,
      'month' => $this->_month($month),
      'day'   => $day,
      'events'=> $cur_event
     );
  $this->load->view('index', $data);
 }
 
 // for convert (int) month to (string) month in Indonesian
 function _month($month){
  $month = (int) $month;
  switch($month){
   case 1 : $month = 'Januari'; Break;
   case 2 : $month = 'Februari'; Break;
   case 3 : $month = 'Maret'; Break;
   case 4 : $month = 'April'; Break;
   case 5 : $month = 'Mei'; Break;
   case 6 : $month = 'Juni'; Break;
   case 7 : $month = 'Juli'; Break;
   case 8 : $month = 'Agustus'; Break;
   case 9 : $month = 'September'; Break;
   case 10 : $month = 'Oktober'; Break;
   case 11 : $month = 'November'; Break;
   case 12 : $month = 'Desember'; Break;
  }
  return $month;
 }
 
 // get detail event for selected date
 function detail_event(){  
  $this->form_validation->set_rules('year', 'Year', 'trim|required|is_natural_no_zero|xss_clean');
  $this->form_validation->set_rules('mon', 'Month', 'trim|required|is_natural_no_zero|less_than[13]|xss_clean');
  $this->form_validation->set_rules('day', 'Day', 'trim|required|is_natural_no_zero|less_than[32]|xss_clean');
  
  if ($this->form_validation->run() == FALSE){
   echo json_encode(array('status' => false, 'title_msg' => 'Error', 'msg' => 'Please insert valid value'));
  }else{
   $data = $this->evencal->getEvent($this->input->post('year'), $this->input->post('mon'), $this->input->post('day'));
   if($data == null){
    echo json_encode(array('status' => false, 'title_msg' => 'No Event', 'msg' => 'There\'s no event in this date'));
   }else{   
    echo json_encode(array('status' => true, 'data' => $data));
   }
  }
 }
 
 // popup for adding event
 function add_event(){
  $data = array(
     'day'   => $this->input->post('day'),
     'mon'   => $this->input->post('mon'),
     'month' => $this->_month($this->input->post('mon')),
     'year'  => $this->input->post('year'),
    );
  $this->load->view('add_event', $data);
 }
 
 // do adding event for selected date
 function do_add(){
  $this->form_validation->set_rules('year', 'Year', 'trim|required|is_natural_no_zero|xss_clean');
  $this->form_validation->set_rules('mon', 'Month', 'trim|required|is_natural_no_zero|less_than[13]|xss_clean');
  $this->form_validation->set_rules('day', 'Day', 'trim|required|is_natural_no_zero|less_than[32]|xss_clean');
  $this->form_validation->set_rules('hour', 'Hour', 'trim|required|xss_clean');
  $this->form_validation->set_rules('minute', 'Minute', 'trim|required|xss_clean');
  $this->form_validation->set_rules('event', 'Event', 'trim|required|xss_clean');
  
  if ($this->form_validation->run() == FALSE){
   echo json_encode(array('status' => false, 'title_msg' => 'Error', 'msg' => 'Please insert valid value'));
  }else{
   $this->evencal->addEvent($this->input->post('year'), 
            $this->input->post('mon'), 
            $this->input->post('day'), 
            $this->input->post('hour').":".$this->input->post('minute').":00",
            $this->input->post('event'));
   echo json_encode(array('status' => true, 'time' => $this->input->post('time'), 'event' => $this->input->post('event')));
  }
 }
 
 // delete event
 function delete_event(){
  $this->form_validation->set_rules('year', 'Year', 'trim|required|is_natural_no_zero|xss_clean');
  $this->form_validation->set_rules('mon', 'Month', 'trim|required|is_natural_no_zero|less_than[13]|xss_clean');
  $this->form_validation->set_rules('day', 'Day', 'trim|required|is_natural_no_zero|less_than[32]|xss_clean');
  $this->form_validation->set_rules('del', 'ID', 'trim|required|is_natural_no_zero|xss_clean');
  
  if ($this->form_validation->run() == FALSE){
   echo json_encode(array('status' => false));
  }else{
   $rows = $this->evencal->deleteEvent($this->input->post('year'),$this->input->post('mon'),$this->input->post('day'), $this->input->post('del'));
   if($rows > 0){
    echo json_encode(array('status' => true, 'row' => $rows));
   }else{
    echo json_encode(array('status' => true, 'row' => $rows, 'title_msg' => 'No Event', 'msg' => 'There\'s no event in this date'));
   }
  }
 }
 
 // same as index() function
 function detail($year = null, $month = null, $day = null){
  $year  = (empty($year) || !is_numeric($year))?  date('Y') :  $year;
  $month = (is_numeric($month) &&  $month > 0 && $month < 13)? $month : date('m');
  $day   = (is_numeric($day) &&  $day > 0 && $day < 31)?  $day : date('d');
  
  $date      = $this->evencal->getDateEvent($year, $month);
  $cur_event = $this->evencal->getEvent($year, $month, $day);
  $data     = array(
      'notes' => $this->calendar->generate($year, $month, $date),
      'year'  => $year,
      'mon'   => $month,
      'month' => $this->_month($month),
      'day'   => $day,
      'events'=> $cur_event
     );
  $this->load->view('index', $data);
 }
 
 // setting for calendar
 function _setting(){
  return array(
   'start_day'   => 'monday',
   'show_next_prev'  => true,
   'next_prev_url'  => site_url('evencal/index'),
   'month_type'     => 'long',
            'day_type'       => 'short',
   'template'    => '{table_open}<table class="date">{/table_open}
           {heading_row_start}&nbsp;{/heading_row_start}
           {heading_previous_cell}<caption><a href="{previous_url}" class="prev_date" title="Previous Month">&lt;&lt;Prev</a>{/heading_previous_cell}
           {heading_title_cell}{heading}{/heading_title_cell}
           {heading_next_cell}<a href="{next_url}" class="next_date"  title="Next Month">Next&gt;&gt;</a></caption>{/heading_next_cell}
           {heading_row_end}<col class="weekday" span="5"><col class="weekend_sat"><col class="weekend_sun">{/heading_row_end}
           {week_row_start}<thead><tr>{/week_row_start}
           {week_day_cell}<th>{week_day}</th>{/week_day_cell}
           {week_row_end}</tr></thead><tbody>{/week_row_end}
           {cal_row_start}<tr>{/cal_row_start}
           {cal_cell_start}<td>{/cal_cell_start}
           {cal_cell_content}<div class="date_event detail" val="{day}"><span class="date">{day}</span><span class="event d{day}">{content}</span></div>{/cal_cell_content}
           {cal_cell_content_today}<div class="active_date_event detail" val="{day}"><span class="date">{day}</span><span class="event d{day}">{content}</span></div>{/cal_cell_content_today}
           {cal_cell_no_content}<div class="no_event detail" val="{day}"><span class="date">{day}</span><span class="event d{day}">&nbsp;</span></div>{/cal_cell_no_content}
           {cal_cell_no_content_today}<div class="active_no_event detail" val="{day}"><span class="date">{day}</span><span class="event d{day}">&nbsp;</span></div>{/cal_cell_no_content_today}
           {cal_cell_blank}&nbsp;{/cal_cell_blank}
           {cal_cell_end}</td>{/cal_cell_end}
           {cal_row_end}</tr>{/cal_row_end}
           {table_close}</tbody></table>{/table_close}');
 }
}

and then for the model evencal_model.php
class Evencal_model extends CI_Model {
 
 // for get all event date in one month
 function getDateEvent($year, $month){
  $year  = ($month < 10 && strlen($month) == 1) ? "$year-0$month" : "$year-$month";
  $query = $this->db->select('event_date, total_events')->from('events')->like('event_date', $year, 'after')->get();
  if($query->num_rows() > 0){
   $data = array();
   foreach($query->result_array() as $row){
    $data[(int) end(explode('-',$row['event_date']))] = $row['total_events'];
   }
   return $data;
  }else{
   return false;
  }
 }
 
 // get event detail for selected date
 function getEvent($year, $month, $day){
  $day   = ($day < 10 && strlen($day) == 1)? "0$day" : $day;
  $year  = ($month < 10 && strlen($month) == 1) ? "$year-0$month-$day" : "$year-$month-$day";
  $query = $this->db->select('idevent as id, event_time as time, event')->order_by('event_time')->get_where('event_detail', array('event_date' => $year));
  if($query->num_rows() > 0){
   return $query->result_array();
  }else{
   return null;
  }
 }
 
 // insert event
 function addEvent($year, $month, $day, $time, $event){ 
  $check = $this->db->get_where('events', array('event_date' => "$year-$month-$day"));
  if($check->num_rows() > 0){
   $this->db->query("UPDATE events SET total_events = total_events + 1 WHERE event_date = ?", array("$year-$month-$day"));
   $this->db->insert('event_detail', array('event_date' => "$year-$month-$day", 'event_time' => $time, 'event' => $event));
  }else{
   $this->db->insert('events', array('event_date' => "$year-$month-$day", 'total_events' => 1));
      $this->db->insert('event_detail', array('event_date' => "$year-$month-$day", 'event_time' => $time, 'event' => $event));
  }
  
 }
 
 // delete event
 function deleteEvent($year, $month, $day, $id){
  $this->db->delete("event_detail", array('idevent' => $id, 'event_date' => "$year-$month-$day"));
  $check = $this->db->query('SELECT count(*) as total FROM event_detail WHERE event_date = ?', array("$year-$month-$day"))->row();
  if($check->total > 0){
   $this->db->update('events', array('total_events' => $check->total), array('event_date' => "$year-$month-$day"));
  }else{
   $this->db->delete("events", array('event_date' => "$year-$month-$day"));
  }
  return $check->total;
 }
}

and for the view, just have 2 views in this application
first view, index.php
<html lang="en">
<head>
 <meta charset="utf-8">
 <title>My Event Calendar (Evencal)</title>
 <link rel="stylesheet" type="text/css" href="<?php echo base_url()?>css/style.css"/>
 <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>css/colorbox.css"/>
 <script type="text/javascript" src="<?php echo base_url();?>js/jquery-1.7.2.min.js"></script>
 <script type="text/javascript" src="<?php echo base_url();?>js/jquery.colorbox-min.js"></script>
</head>
<body>
 <div id="evencal">
  <div class="calendar">
   <?php echo $notes?>
   <span>by <a href="http://zawaruddin.blogspot.com"><strong>zawaruddin.blogspot.com</strong></a></span>
  </div>
  <div class="event_detail">
   <h2 class="s_date">Detail Event <?php echo "$day $month $year";?></h2>
   <div class="detail_event">
    <?php 
     if(isset($events)){
      $i = 1;
      foreach($events as $e){
       if($i % 2 == 0){
        echo '<div class="info1"><h4>'.$e['time'].'<img src="'.base_url().'css/images/delete.png" class="delete" alt="" title="delete this event" day="'.$day.'" val="'.$e['id'].'" /></h4><p>'.$e['event'].'</p></div>';
       }else{
        echo '<div class="info2"><h4>'.$e['time'].'<img src="'.base_url().'css/images/delete.png" class="delete" alt="" title="delete this event" day="'.$day.'" val="'.$e['id'].'" /></h4><p>'.$e['event'].'</p></div>';
       } 
       $i++;
      }
     }else{
      echo '<div class="message"><h4>No Event</h4><p>There\'s no event in this date</p></div>';
     }
    ?>
    <input type="button" name="add" value="Add Event" val="<?php echo $day;?>" class="add_event"/>
   </div>
  </div>
 </div>
 <script>
  $(".detail").live('click',function(){
   $(".s_date").html("Detail Event for "+$(this).attr('val')+" <?php echo "$month $year";?>");
   var day = $(this).attr('val');
   var add = '<input type="button" name="add" value="Add Event" val="'+day+'" class="add_event"/>';
   $.ajax({
    type: 'post',
    dataType: 'json',
    url: "<?php echo site_url("evencal/detail_event");?>",
    data:{<?php echo "year: $year, mon: $mon";?>, day: day},
    success: function( data ) {
     var html = '';
     if(data.status){
      var i = 1;
      $.each(data.data, function(index, value) {
          if(i % 2 == 0){
        html = html+'<div class="info1"><h4>'+value.time+'<img src="<?php echo base_url();?>css/images/delete.png" class="delete" alt="" title="delete this event" day="'+day+'" val="'+value.id+'" /></h4><p>'+value.event+'</p></div>';
       }else{
        html = html+'<div class="info2"><h4>'+value.time+'<img src="<?php echo base_url();?>css/images/delete.png" class="delete" alt="" title="delete this event" day="'+day+'" val="'+value.id+'" /></h4><p>'+value.event+'</p></div>';
       } 
       i++;
      });
     }else{
      html = '<div class="message"><h4>'+data.title_msg+'</h4><p>'+data.msg+'</p></div>';
     }
     html = html+add;
     $( ".detail_event" ).fadeOut("slow").fadeIn("slow").html(html);
    } 
   });
  });
  $(".delete").live("click", function() {
   if(confirm('Are you sure delete this event ?')){
    var deleted = $(this).parent().parent();
    var day =  $(this).attr('day');
    var add = '<input type="button" name="add" value="Add Event" val="'+day+'" class="add_event"/>';
    $.ajax({
     type: 'POST',
     dataType: 'json',
     url: "<?php echo site_url("evencal/delete_event");?>",
     data:{<?php echo "year: $year, mon: $mon";?>, day: day,del: $(this).attr('val')},
     success: function(data) {
      if(data.status){
       if(data.row > 0){
        $('.d'+day).html(data.row);
       }else{
        $('.d'+day).html('');
        $( ".detail_event" ).fadeOut("slow").fadeIn("slow").html('<div class="message"><h4>'+data.title_msg+'</h4><p>'+data.msg+'</p></div>'+add);
       }
       deleted.remove();
      }else{
       alert('an error for deleting event');
      }
     }
    });
   }
  });
  $(".add_event").live('click', function(){
   $.colorbox({ 
     overlayClose: false,
     href: '<?php echo site_url('evencal/add_event');?>',
     data:{year:<?php echo $year;?>,mon:<?php echo $mon;?>, day: $(this).attr('val')}
   });
  });
</script>
</body>
</html>

and second view for add event form, add_event.php
<?php 
 $h = '<select name="hour" id="hour">';
 $m = '<select name="minute" id="minute">';
 for($i = 0; $i< 60; $i++){
  if($i < 24){
   $h .= '<option value="'.(($i > 9)? $i : "0$i").'">'.(($i > 9)? $i : "0$i").'</option>';
  }
  $m .= '<option value="'.(($i > 9)? $i : "0$i").'">'.(($i > 9)? $i : "0$i").'</option>';
 }
 $h .= '</select>';
 $m .= '</select>';
?>
<div style="width:500px; height:135px; overflow:auto; color:#000000; margin-bottom:20px;" align="center">
 <h4>Adding event for <?php echo "$day $month $year"?></h4>
 <div class="spacer"></div>
 <table>
  <tr><td>Time <span class="require">*</span></td><td>:</td><td><?php echo "$h&nbsp;:&nbsp;$m";?>&nbsp;:&nbsp;<select name="second" disabled><option value="00">00</option></select></td></tr>
  <tr><td>Event <span class="require">*</span></td><td>:</td><td><input type="text" name="event" id="event" maxlength="50" size="50" /></td></tr>
  <tr><td colspan="2"></td><td><input type="button" name="cancel" value="Cancel" class="cancel">&nbsp;&nbsp;
          <input type="button" name="save" value="Save" class="save"></td></tr>
 </table>
 <script> 
 $('.cancel').click(function(){
  var data = false;
  $.fn.colorbox.close(data);
 });
 $('.save').click(function(){
  if($('#event').val().length > 0){
   $.ajax({
    type: 'POST',
    dataType: 'json',
    url: "<?php echo site_url("evencal/do_add");?>",
    data:{<?php echo "year:$year,mon:$mon,day:$day";?>, hour:$('#hour').val(), minute: $('#minute').val(), event:$('#event').val()},
    success: function(data) {
     if(data.status){
      //$.fn.colorbox.close(data);
      window.location = '<?php echo site_url("evencal/detail/$year/$mon/$day")?>';
     }else{
      $('.spacer').html(data.message);
     }
    }
   });
  }else{
   $('.spacer').html('Please complete the field')
   $('#event').attr('class','error_require');
  }
 });
 </script>
</div>

and last, for autoload component in codeigniter
$autoload['libraries'] = array('database','form_validation');
$autoload['helper'] = array('url','form','html');

That's all about my sharing for Multiple Event Calendar - Evencal with codeigniter.
Sorry about my english :D
You can download the source in my github repo.

Keywords : Codeigniter Multiple Event Calendar,  Event Calendar, Calendar

To appreciate the IPR (Intellectual Property Rights), reference sources that I use and I have learned will be displayed.
Referensi    : Codeigniter User Guide,
                    www.paulund.co.uk/giveaway-10-css-notification-boxes-for-free
                    www.jacklmoore.com/colorbox
Author        : Moch. Zawaruddin Abdullah, www.zawaruddin.blogspot.com