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. The dynamic event calendar can be easily built with PHP and MySQL.
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 the sample CodeIgniter Event Calendar, the following functionality will be implemented.
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
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.
CREATE TABLE `events` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`date` date NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
The Calendar controller helps to generate event calendar and display calendar in the full view.
eventCalendar()
method.getRows()
method of the Event model.<?php defined('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', $data, true);
}
}
/*
* 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 .= '<option value="'.$value.'" '.$selectedOpt.' >'.date("F", mktime(0, 0, 0, $i+1, 0, 0)).'</option>';
}
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 .= '<option value="'.$i.'" '.$selectedOpt.' >'.$i.'</option>';
}
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 = '<h2 class="sidebar__heading">'.date("l", strtotime($date)).'<br>'.date("F d, Y", strtotime($date)).'</h2>';
if(!empty($events)){
$eventListHTML .= '<ul class="sidebar__list">';
$eventListHTML .= '<li class="sidebar__list-item sidebar__list-item--complete">Events</li>';
$i = 0;
foreach($events as $row){ $i++;
$eventListHTML .= '<li class="sidebar__list-item"><span class="list-item__time">'.$i.'.</span>'.$row['title'].'</li>';
}
$eventListHTML .= '</ul>';
}
if($return == 'return'){
return $eventListHTML;
}else{
echo $eventListHTML;
}
}
}
The Event model handles the database related operations.
$params
. Returns the data array on success, and FALSE on error.<?php defined('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;
}
}
1. calendar/
1.1. index.php
Display the event calendar passed by the index()
method of the Calendar controller.
<!-- Display event calendar -->
<div id="calendar_div">
<?php echo $eventCalendar; ?>
</div>
Include the jQuery library.
<!-- jQuery library -->
<script src="<?php echo base_url('assets/js/jquery.min.js'); ?>"></script>
The following code is used to get the calendar and events data using jQuery and Ajax.
eventCalendar()
method of Calendar controller.getEvents()
method of Calendar controller.<script>
function getCalendar(target_div, year, month){
$.get( '<?php echo base_url('calendar/eventCalendar/'); ?>'+year+'/'+month, function( html ) {
$('#'+target_div).html(html);
});
}
function getEvents(date){
$.get( '<?php echo base_url('calendar/getEvents/'); ?>'+date, function( html ) {
$('#event_list').html(html);
});
}
</script>
The following code helps to change the calendar days by changing the year or month dropdown.
<script>
$(document).on("change", ".month-dropdown", function(){
getCalendar('calendar_div', $('.year-dropdown').val(), $('.month-dropdown').val());
});
$(document).on("change", ".year-dropdown", function(){
getCalendar('calendar_div', $('.year-dropdown').val(), $('.month-dropdown').val());
});
</script>
1.2. event-cal.php
Create a large calendar and add events to this calendar.
<main class="calendar-contain">
<section class="title-bar">
<a href="javascript:void(0);" class="title-bar__prev" onclick="getCalendar('calendar_div','<?php echo date("Y",strtotime($calendar['date'].' - 1 Month')); ?>','<?php echo date("m",strtotime($calendar['date'].' - 1 Month')); ?>');"></a>
<div class="title-bar__month">
<select class="month-dropdown">
<?php echo $monthOptions; ?>
</select>
</div>
<div class="title-bar__year">
<select class="year-dropdown">
<?php echo $yearOptions; ?>
</select>
</div>
<a href="javascript:void(0);" class="title-bar__next" onclick="getCalendar('calendar_div','<?php echo date("Y",strtotime($calendar['date'].' + 1 Month')); ?>','<?php echo date("m",strtotime($calendar['date'].' + 1 Month')); ?>');"></a>
</section>
<aside class="calendar__sidebar" id="event_list">
<?php echo $eventList; ?>
</aside>
<section class="calendar__days">
<section class="calendar__top-bar">
<span class="top-bar__days">Mon</span>
<span class="top-bar__days">Tue</span>
<span class="top-bar__days">Wed</span>
<span class="top-bar__days">Thu</span>
<span class="top-bar__days">Fri</span>
<span class="top-bar__days">Sat</span>
<span class="top-bar__days">Sun</span>
</section>
<?php
$dayCount = 1;
$eventNum = 0;
echo '<section class="calendar__week">';
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 '
<div class="calendar__day today" onclick="getEvents(\''.$currentDate.'\');">
<span class="calendar__date">'.$dayCount.'</span>
<span class="calendar__task calendar__task--today">'.$eventNum.' Events</span>
</div>
';
}elseif($eventNum > 0){
echo '
<div class="calendar__day event" onclick="getEvents(\''.$currentDate.'\');">
<span class="calendar__date">'.$dayCount.'</span>
<span class="calendar__task">'.$eventNum.' Events</span>
</div>
';
}else{
echo '
<div class="calendar__day no-event" onclick="getEvents(\''.$currentDate.'\');">
<span class="calendar__date">'.$dayCount.'</span>
<span class="calendar__task">'.$eventNum.' Events</span>
</div>
';
}
$dayCount++;
}else{
if($cb < $calendar['currentMonthFirstDay']){
$inactiveCalendarDay = ((($calendar['totalDaysOfMonth_Prev']-$calendar['currentMonthFirstDay'])+1)+$cb);
$inactiveLabel = 'expired';
}else{
$inactiveCalendarDay = ($cb-$calendar['totalDaysOfMonthDisplay']);
$inactiveLabel = 'upcoming';
}
echo '
<div class="calendar__day inactive">
<span class="calendar__date">'.$inactiveCalendarDay.'</span>
<span class="calendar__task">'.$inactiveLabel.'</span>
</div>
';
}
echo ($cb%7 == 0 && $cb != $calendar['boxDisplay'])?'</section><section class="calendar__week">':'';
}
echo '</section>';
?>
</section>
</main>
How to Highlight Specific Dates in jQuery UI Datepicker
Our example code helps you to integrate the event calendar functionality in the CodeIgniter website. The events can be displayed in the calendar dynamically from the database. This calendar allows navigating to the different months without page refresh using jQuery and Ajax. You can easily enhance the functionality of the CodeIgniter event calendar as per your needs.
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
this was very helpful for my college project, thanks a lot