loading

How to Build an Event Calendar in CodeIgniter using jQuery

How to Build an Event Calendar in CodeIgniter using jQuery

How to Build an Event Calendar in CodeIgniter using jQuery

0 Sales

Free

The Event Calendar facilitates the listing of events from the database in a user-friendly manner. The full view calendar is the greatest solution for dynamically displaying events in a calendar. The events are retrieved from the database and shown on the huge calendar via the dynamic web application. PHP and MySQL can be used to simply create a dynamic event calendar.

The event calendar feature must be included into the CodeIgniter application if your web application is created with the CodeIgniter framework. In CodeIgniter, you can quickly design a custom event calendar to show events from the database. In this article, we will teach you how to design an event calendar in CodeIgniter using jQuery and Ajax.

The following functionality will be implemented in the sample CodeIgniter Event Calendar.

 - Data from events is retrieved from the MySQL database.
 - Using HTML and CSS, create a full-view calendar.
 - Display events in the calendar's date cell.
 - Using jQuery and Ajax, navigate between the months and years.

Take a look at the file structure before beginning to build an event calendar script for CodeIgniter.

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

A table in the database is required to store the dynamic events data. In the MySQL database, the following SQL creates an events table with some basic columns.

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;

Controller (Calendar.php)

The Calendar controller aids in the generation of event calendars and the presentation of calendars in full view.

1. __construct() – Initialize the Event model.
2. index() –

 - Retrieve the event calendar by using the eventCalendar() function.
 - The calendar HTML should be sent to the view.
3. eventCalendar() –

 - Create a calendar of events depending on the year and month.
 - Activate the calendar view.
4. getMonths() – Generate a list of months possibilities for the pick box.
5. getYears() – Generate a list of years possibilities for the pick box.
6. getEvents() –

 - Retrieve events from the database using the Event model's getRows() function.
 - Create an HTML version of the event listings.

<?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'$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 .= '<option value="'.$value.'" '.$selectedOpt.' >'.date("F"mktime(000$i+100)).'</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;     
        } 
    } 
}

 

Model (Event.php)

The database operations are handled by the Event model.

1. __construct() – Define the name of the table.
2. getRows() – Retrieve the events data from the database depending on the parameters supplied in $params. If successful, returns the data array; otherwise, returns FALSE.
3. getGroupCount() – Groups events by date and provides data with the event number for each date.

<?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; 
    } 
}

View

1. calendar/

1.1. index.php

Display the event calendar supplied by the Calendar controller's index() function.

<!-- Display event calendar -->
<div id="calendar_div">
    <?php echo $eventCalendar?>
</div>

Incorporate the jQuery library.

<!-- jQuery library -->
<script src="<?php echo base_url('assets/js/jquery.min.js'); ?>"></script>

Using jQuery and Ajax, the following code retrieves calendar and event data.

 - The getCalendar() function initiates an Ajax call to retrieve calendar HTML from the Calendar controller's eventCalendar() method.
 - The getEvents() function initiates an Ajax call to retrieve the events list from the Calendar controller's getEvents() method.

<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 code below assists in adjusting the calendar days by changing the year or month option.

<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

Make a huge calendar and start adding events to it.

 - To browse to a different month, a year and month selection is available in the header.
 - There is a Next and Prev button to browse to the next and previous month.
 - The number of events is stored in each date field. A tooltip showing the event number for the selected date shows when you hover over it.
 - The events are listed at the top of the calendar when you click the event number.

<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%== && $cb != $calendar['boxDisplay'])?'</section><section class="calendar__week">':''; 
            } 
            echo '</section>'; 
        ?>
    </section>
</main>

Conclusion

Our sample code will assist you in incorporating the event calendar feature into your CodeIgniter website. The events may be dynamically shown in the calendar from the database. Using jQuery and Ajax, this calendar allows you to navigate to other months without refreshing the page. You may simply customise the functionality of the CodeIgniter event calendar to meet your specific requirements.

 

 

LICENSE OF USE

You can use it for personal or commercial projects. You can't resell it partially or in this form.

PRODUCT INFO

Create Date : Jan 25, 2022

Updated Date : Jan 25, 2022

Ratings

Comments : 0

Downloads : 0