IMG-LOGO
Home Tutorial Event Calendar in CodeIgniter

Event Calendar in CodeIgniter

by MH RISHAD - 24 Nov 2020
IMG

Event Calendar helps to list the events from the database in a user-friendly way. The full view calendar is the best option to display the events dynamically in a calendar. In the dynamic web application, the events are fetched from the database and listed in the large calendar.

If your web application built with the CodeIgniter framework, the event calendar functionality needs to integrate into the CodeIgniter application. You can easily create a custom event calendar to display events from the database in CodeIgniter. In this tutorial, we will show you how to build an event calendar in CodeIgniter using jQuery and Ajax.

In CodeIgniter Event Calendar, the following functionality will be implemented.

  • Fetch events data from the MySQL database.
  • Create a full-view calendar with HTML and CSS.
  • Display events in the date cell of the calendar.
  • Navigate between the months and years using jQuery and Ajax.

Before getting started to build an event calendar script for CodeIgniter, take a look at the file structure.

codeigniter_event_calendar/

├── application/

   ├── controllers/

      └── Calendar.php

   ├── models/

      └── Event.php

   └── views/

       └── calendar/

           ├── index.php

           └── event-cal.php

└── assets/

    ├── js/

       └── jquery.min.js

    └── css/

        └── style.css

Create Database Table

To store the dynamic events data a table is required in the database. The following SQL creates an events table with some basic fields in the MySQL database.

 

Controller (Calendar.php)

The Calendar controller helps to generate event calendar and display calendar in the full view.

1.            __construct() – Load the Event model.

  1. index() –
    • Get event calendar using eventCalendar() method.
    • Pass the calendar HTML to the view.

3.    eventCalendar() –

    • Build event calendar based on the year and month.
    • Load calendar view.

4.    getMonths() – Generate months options list for the select box.

  1. getYears() – Generate years options list for the select box.
  2. getEvents() –
    • Fetch events from the database using getRows() method of the Event model.
    • Generate an HTML view of the event lists.

 

('BASEPATH') OR exit('No direct script access allowed');
 
class 
Calendar extends CI_Controller {
    
    function 
__construct() {
        
parent::__construct();
        
        
$this->load->model('event');
    }
    
    public function 
index(){
        
$data = array();
        
$data['eventCalendar'] = $this->eventCalendar();
        
$this->load->view('calendar/index'$data);
    }
    
    
/*
     * Generate calendar with events
     */
    
public function eventCalendar($year ''$month ''){
        
$data = array();
        
        
$dateYear = ($year != '')?$year:date("Y");
        
$dateMonth = ($month != '')?$month:date("m");
        
$date $dateYear.'-'.$dateMonth.'-01';
        
$eventDate = empty($year) && empty($month)?date("Y-m-d"):$date;
        
$currentMonthFirstDay date("N"strtotime($date));
        
$totalDaysOfMonth cal_days_in_month(CAL_GREGORIAN$dateMonth$dateYear);
        
$totalDaysOfMonthDisplay = ($currentMonthFirstDay == 1)?($totalDaysOfMonth):($totalDaysOfMonth + ($currentMonthFirstDay 1));
        
$boxDisplay = ($totalDaysOfMonthDisplay <= 35)?35:42;
        
        
$prevMonth date("m"strtotime('-1 month'strtotime($date)));
        
$prevYear date("Y"strtotime('-1 month'strtotime($date)));
        
$totalDaysOfMonth_Prev cal_days_in_month(CAL_GREGORIAN$prevMonth$prevYear);
        
        
$con = array(
            
'where' => array(
                
'status' => 1
            
),
            
'where_year' => $dateYear,
            
'where_month' => $dateMonth
        
);
        
$data['events'] = $this->event->getGroupCount($con);
        
        
$data['calendar'] = array(
            
'dateYear' => $dateYear,
            
'dateMonth' => $dateMonth,
            
'date' => $date,
            
'currentMonthFirstDay' => $currentMonthFirstDay,
            
'totalDaysOfMonthDisplay' => $totalDaysOfMonthDisplay,
            
'boxDisplay' => $boxDisplay,
            
'totalDaysOfMonth_Prev' => $totalDaysOfMonth_Prev
        
);
        
        
$data['monthOptions'] = $this->getMonths($dateMonth);
        
$data['yearOptions'] = $this->getYears($dateYear);
        
$data['eventList'] = $this->getEvents($eventDate'return');
 
        if(!empty(
$_SERVER['HTTP_X_REQUESTED_WITH'])){
            
$this->load->view('calendar/event-cal'$data);
        }else{
            return 
$this->load->view('calendar/event-cal'$datatrue);
        }
    }
    
    
/*
     * Generate months options list for select box
     */
    
function getMonths($selected ''){
        
$options '';
        for(
$i=1;$i<=12;$i++)
        {
            
$value = ($i 10)?'0'.$i:$i;
            
$selectedOpt = ($value == $selected)?'selected':'';
            
$options .= '.$value.'" '.$selectedOpt.' >'.date("F", mktime(0, 0, 0, $i+1, 0, 0)).'';
        }
        return 
$options;
    }
   
    
/*
     * Generate years options list for select box
     */
    
function getYears($selected ''){
        
$yearInit = !empty($selected)?$selected:date("Y");
        
$yearPrev = ($yearInit 5);
        
$yearNext = ($yearInit 5);
        
$options '';
        for(
$i=$yearPrev;$i<=$yearNext;$i++){
            
$selectedOpt = ($i == $selected)?'selected':'';
            
$options .= '.$i.'" '.$selectedOpt.' >'.$i.'';
        }
        return 
$options;
    }
   
    
/*
     * Generate events list in HTML format
     */
    
function getEvents($date ''$return='view'){
        
$date $date?$date:date("Y-m-d");
        
        
// Fetch events based on the specific date
        
$con = array(
            
'where' => array(
                
'date' => $date,
                
'status' => 1
            
)
        );
        
$events $this->event->getRows($con);
        
        
$eventListHTML '

.date("l"strtotime($date)).'
'
.date("F d, Y"strtotime($date)).'';
        if(!empty(
$events)){
            
$eventListHTML .= '

;
            
$eventListHTML .= '

';
            
$i 0;
            foreach(
$events as $row){ $i++;
                
$eventListHTML .= '
.$row['title'].'';
            }
            
$eventListHTML .= '';
        }
        
        if(
$return == 'return'){
            return 
$eventListHTML;
        }else{
            echo 
$eventListHTML;    
        }
    }
}

 

 

Model (Event.php)

The Event model handles the database related operations.

1.            __construct() – Define the table name.

  1. getRows() – Fetch the events data from the database based on the conditions specified in $params. Returns the data array on success, and FALSE on error.
  2. getGroupCount() – Grouped by the events based on the date and returns data with event number for each date.

('BASEPATH') OR exit('No direct script access allowed');
 
class 
Event extends CI_Model{
    function 
__construct() {
        
// Set table name
        
$this->table 'events';
    }
    
    
/*
     * Fetch event data from the database
     * @param array filter data based on the passed parameters
     */
    
function getRows($params = array()){
        
$this->db->select('*');
        
$this->db->from($this->table);
        
        if(
array_key_exists("where"$params)){
            foreach(
$params['where'] as $key => $val){
                
$this->db->where($key$val);
            }
        }
        
        if(
array_key_exists("returnType",$params) && $params['returnType'] == 'count'){
            
$result $this->db->count_all_results();
        }else{
            if(
array_key_exists("id"$params) || (array_key_exists("returnType"$params) && $params['returnType'] == 'single')){
                if(!empty(
$params['id'])){
                    
$this->db->where('id'$params['id']);
                }
                
$query $this->db->get();
                
$result $query->row_array();
            }else{
                
$this->db->order_by('date''asc');
                if(
array_key_exists("start",$params) && array_key_exists("limit",$params)){
                    
$this->db->limit($params['limit'],$params['start']);
                }elseif(!
array_key_exists("start",$params) && array_key_exists("limit",$params)){
                    
$this->db->limit($params['limit']);
                }
                
                
$query $this->db->get();
                
$result = ($query->num_rows() > 0)?$query->result_array():FALSE;
            }
        }
        
        
// Return fetched data
        
return $result;
    }
    
    
/*
     * Fetch and group by events based on date
     * @param array filter data based on the passed parameters
     */
    
function getGroupCount($params = array()){
        
$this->db->select("date, COUNT(id) as event_num");
        
$this->db->from($this->table);
        
        if(
array_key_exists("where"$params)){
            foreach(
$params['where'] as $key => $val){
                
$this->db->where($key$val);
            }
        }
        
        if(
array_key_exists("where_year"$params)){
            
$this->db->where("YEAR(date) = ".$params['where_year']);
        }
        
        if(
array_key_exists("where_month"$params)){
            
$this->db->where("MONTH(date) = ".$params['where_month']);
        }
        
        
$this->db->group_by('date');
        
        
$query $this->db->get();
        
$result = ($query->num_rows() > 0)?$query->result_array():FALSE;
        
        
// Return fetched data
        
return $result;
    }
}

View

1. calendar/

1.1. index.php
Display the event calendar passed by the 
index() method of the Calendar controller.

"calendar_div">

    echo $eventCalendar?>

 

Include the jQuery library.

 

The following code is used to get the calendar and events data using jQuery and Ajax.

  • The getCalendar() function Initiate Ajax request to get calendar HTML from eventCalendar() method of Calendar controller.
  • The getEvents() function Initiate Ajax request to get events list from getEvents() method of Calendar controller.

 

The following code helps to change the calendar days by changing the year or month dropdown.

 

1.2. event-cal.php
Create a large calendar and add events to this calendar.

  • In the header, year and month dropdown is provided to navigate to the different month.
  • Next and Prev button is provided to navigate to the next and previous month.
  • Each date cell holds the number of the events. On hover, a tooltip appears with the event number for the selected date.
  • By clicking the event number, the events are listed at the top of the calendar.
"calendar-contain">

   

"title-bar">

        "javascript:void(0);" class="title-bar__prev" onclick="getCalendar('calendar_div','echo date("Y",strtotime($calendar['date'].' - 1 Month')); ?>','echo date("m",strtotime($calendar['date'].' - 1 Month')); ?>');">

       

"title-bar__month">

            "month-dropdown">

                echo $monthOptions?>

           

       

       

"title-bar__year">

            "year-dropdown">

                echo $yearOptions?>

           

       

        "javascript:void(0);" class="title-bar__next" onclick="getCalendar('calendar_div','echo date("Y",strtotime($calendar['date'].' + 1 Month')); ?>','echo date("m",strtotime($calendar['date'].' + 1 Month')); ?>');">

        echo $eventList?>

"calendar__days">      
"calendar__top-bar">

            "top-bar__days">Mon

            "top-bar__days">Tue

            "top-bar__days">Wed

            "top-bar__days">Thu

            "top-bar__days">Fri

            "top-bar__days">Sat

            "top-bar__days">Sun 

            $dayCount 1;
            
$eventNum 0;
            
            echo '
';
            for(
$cb=1;$cb<=$calendar['boxDisplay'];$cb++){
                if((
$cb >= $calendar['currentMonthFirstDay'] || $calendar['currentMonthFirstDay'] == 1) && $cb <= $calendar['totalDaysOfMonthDisplay']){
                    
// Current date
                    
$dayCount = ($dayCount 10 && strpos($dayCount'0') == false)?'0'.$dayCount:$dayCount;
                    
$currentDate $calendar['dateYear'].'-'.$calendar['dateMonth'].'-'.$dayCount;
                    
                    
// Get number of events based on the current date
                    
$eventNum 0;
                    if(!empty(
$events)){
                        
$eventData array_filter($events, function ($var) use ($currentDate) {
                            return (
$var['date'] == $currentDate);
                        });
                        
$eventData array_values($eventData);
                        
$eventData = !empty($eventData[0])?$eventData[0]:'';
                        
$eventNum = !empty($eventData['event_num'])?$eventData['event_num']:0;
                    }
                    
                    
// Define date cell color
                    
if(strtotime($currentDate) == strtotime(date("Y-m-d"))){
                        echo 
'.$currentDate.'\');">
                                '.$dayCount.'
                                '.$eventNum.' Events
                            
                        ';
                    }elseif(
$eventNum 0){
                        echo 
'
                         
.$currentDate.'\');">
                                '.$dayCount.'
                                '.$eventNum.' Events
                            
                        ';
                    }else{
                        echo 
'.$currentDate.'\');">
                                '.$dayCount.'
                                '.$eventNum.' Events
';
                    }
                    
$dayCount++;
                }else{
                    if(
$cb $calendar['currentMonthFirstDay']){
                        
$inactiveCalendarDay = ((($calendar['totalDaysOfMonth_Prev']-$calendar['currentMonthFirstDay'])+1)+$cb);
                        
$inactiveLabel 'expired';
                    }else{
                        
$inactiveCalendarDay = ($cb-$calendar['totalDaysOfMonthDisplay']);
                        
$inactiveLabel 'upcoming';
                    }
                    echo 
''.$inactiveCalendarDay.'  '.$inactiveLabel.'
                                            ';
                }
                echo (
$cb%== && $cb != $calendar['boxDisplay'])?':'';
            }
            echo 
'';
        
?>

   

 Thank You

Share:

Leave a Comment

Required fields are marked *