CodeIgniter 4 FullCalendar Example Tutorial

             Integrating FullCalendar with events in CodeIgniter 4 is a straightforward process that provides a powerful and responsive calendar system for your application. FullCalendar is an open-source jQuery library that allows you to create, edit, and manage events efficiently. With drag-and-drop functionality and customization options, FullCalendar makes event handling seamless.

CodeIgniter 4 FullCalender: Integrate FullCalendar with Events

Table Of Content

1 Prerequisites

1.) PHP version of >= 8.2
2.) Composer
3.) Mysql

2 Introduction

This guide walks you through an example of creating a CRUD application in CodeIgniter 4 to manage events using FullCalendar. You will set up a database, create a migration, define a model, and implement a controller to handle FullCalendar operations.

3 Create / Install a Codeigniter 4 Project

3.1 Install Codeigniter 4 Project

Install CodeIgniter 4 using Composer:

composer create-project codeigniter4/appstarter ci-4-fullcalendar-app

Then, navigate to your project directory:

cd ci-4-fullcalendar-app

3.2 Configure Environment and MySql Database

Rename .env and update the database configuration:

# CI_ENVIRONMENT = production
CI_ENVIRONMENT = development


DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=ci4_fullcalender
DB_USERNAME=root
DB_PASSWORD=

4 Create Migration and Model

Generate a migration for the events table and define its structure:

php spark make:model Event

Edit app/Models/Event.php to configure the model:

<?php
namespace App\Models;

use CodeIgniter\Model;

class Event extends Model
{
    protected $table = 'events';
    protected $primaryKey = 'id';
    protected $allowedFields = ['title','start','end', 'created_at','updated_at'];
}

Update the migration file to include fields for the event table, such as title, start, end, created_at, and updated_at.

php spark make:migration AddEvent

Edit the migration file to define the table structure:
    
<?php
namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class CreateEventsTable extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
                'type' => 'BIGINT',
                'constraint' => 255,
                'unsigned' => true,
                'auto_increment' => true
            ],
            'title' => [
                'type' => 'VARCHAR',
                'constraint' => '255',
            ],
           'start' => [
                'type' => 'DATE',
                'null' => true
            ],
            'end' => [
                'type' => 'DATE',
                'null' => true
            ],
            'created_at' => [
                'type' => 'TIMESTAMP',
                'null' => true
            ],
            'updated_at' => [
                'type' => 'TIMESTAMP',
                'null' => true
            ],
        ]);
        $this->forge->addPrimaryKey('id');
        $this->forge->createTable('events');
    }

    public function down()
    {
        $this->forge->dropTable('events');
    }
}

Run the migration:

php spark migrate

5 Create Database Seeder

For seeding test data in the events table, use the Seeder class:

php spark make:seeder EventSeeder

Inside the EventSeeder.php file, use the Faker library to generate fake data:

<?php
namespace App\Database\Seeds;

use CodeIgniter\Database\Seeder;
use CodeIgniter\I18n\Time;
use App\Models\Event;

class EventSeeder extends Seeder
{
    public function run()
    {
        $event = new Event;
        $faker = \Faker\Factory::create();

        for ($i = 0; $i < 10; $i++) {

            $start = $faker->dateTimeBetween('next Monday', 'next Monday +7 days');
            $end = $faker->dateTimeBetween($start, $start->format('Y-m-d').' +3 days');


          $event->save(
                [
                    'title'        =>    $faker->name,
                    'start'        =>    $start->format('Y-m-d'),
                    'end' => $end->format('Y-m-d'),
                    'created_at'  =>    Time::createFromTimestamp($faker->unixTime()),
                    'updated_at'  =>    Time::now()
                ]
            );
        }
    }
}

Run this below command to insert the data.

php spark db:seed EventSeeder

6 Create New Controller - FullCalenderController

Create a controller, This will handle operations like adding, updating, and deleting events.

php spark make:controller FullCalenderController

In app/Controllers/FullCalenderController.php, define the index and ajax function:

<?php
namespace App\Controllers;

use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\Event;

class FullCalenderController extends BaseController
{
    public function index()
    {

       if(!empty($this->request->getGet('start')))
       {
            $event = new Event();
            $data = $event->where('start>=',$this->request->getGet('start'))->where('end<=',$this->request->getGet('end'))->findAll();
            return response()->setJSON($data);
       }
        return view('fullcalender');
    }

    public function ajax()
    {
 
        $event = new Event();
        switch ($this->request->getPost('type')) {
           case 'add':
            $data = [
                "title" => $this->request->getPost("title"),
                "start" => $this->request->getPost("start"),
                "end" => $this->request->getPost("end"),
            ];
            $event_id=$event->insert($data);
            $eventData=$event->find($event_id);
            return response()->setJSON($eventData);
             break;
  
           case 'update':
            $data = [
                "title" => $this->request->getPost("title"),
                "start" => $this->request->getPost("start"),
                "end" => $this->request->getPost("end"),
            ];
            $event_id= $event->update( $this->request->getPost("id"), $data);
            $eventData=$event->find($event_id);
            return response()->setJSON($eventData);
             break;
  
           case 'delete':
              $eventData = $event->where("id",$this->request->getPost("id"))->delete();
              return response()->setJSON($eventData);
             break;
             
           default:
             # code...
             break;
        }
    }
}
?>

7 Create a View

Develop a view file (index.php) to display the FullCalendar. Include the FullCalendar and jQuery libraries for rendering and interaction.

    <!DOCTYPE html>
<html>
<head>
    <title>Codeigniter 4 Fullcalender Tutorial Tutorial - GetSampleCode.com</title>
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.9.0/fullcalendar.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.9.0/fullcalendar.js"></script>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" />
</head>
<body>
    
<div class="container">
    <div class="card mt-5">
        <h3 class="card-header p-3">Codeigniter 4 FullCalender Tutorial Example - GetSampleCode.com</h3>
        <div class="card-body">
            <div id='calendar'></div>
        </div>
    </div>
</div>
  
<script type="text/javascript">
  
$(document).ready(function () {
      
    var calendar = $('#calendar').fullCalendar({
                    editable: true,
                    events: "fullcalender",
                    displayEventTime: false,
                    editable: true,
                    eventRender: function (event, element, view) {
                        if (event.allDay === 'true') {
                                event.allDay = true;
                        } else {
                                event.allDay = false;
                        }
                    },
                    selectable: true,
                    selectHelper: true,
                    select: function (start, end, allDay) {
                        var title = prompt('Event Title:');
                        if (title) {
                            var start = $.fullCalendar.formatDate(start, "Y-MM-DD");
                            var end = $.fullCalendar.formatDate(end, "Y-MM-DD");
                            $.ajax({
                                url: "/fullcalenderAjax",
                                data: {
                                    title: title,
                                    start: start,
                                    end: end,
                                    type: 'add'
                                },
                                type: "POST",
                                success: function (data) {
                                    displayMessage("Event Created Successfully");
  
                                    calendar.fullCalendar('renderEvent',
                                        {
                                            id: data.id,
                                            title: title,
                                            start: start,
                                            end: end,
                                            allDay: allDay
                                        },true);
  
                                    calendar.fullCalendar('unselect');
                                }
                            });
                        }
                    },
                    eventDrop: function (event, delta) {
                        var start = $.fullCalendar.formatDate(event.start, "Y-MM-DD");
                        var end = $.fullCalendar.formatDate(event.end, "Y-MM-DD");
  
                        $.ajax({
                            url: '/fullcalenderAjax',
                            data: {
                                title: event.title,
                                start: start,
                                end: end,
                                id: event.id,
                                type: 'update'
                            },
                            type: "POST",
                            success: function (response) {
                                displayMessage("Event Updated Successfully");
                            }
                        });
                    },
                    eventClick: function (event) {
                        var deleteMsg = confirm("Do you really want to delete?");
                        if (deleteMsg) {
                            $.ajax({
                                type: "POST",
                                url: '/fullcalenderAjax',
                                data: {
                                        id: event.id,
                                        type: 'delete'
                                },
                                success: function (response) {
                                    calendar.fullCalendar('removeEvents', event.id);
                                    displayMessage("Event Deleted Successfully");
                                }
                            });
                        }
                    }
 
                });
 
    });
      
    /*------------------------------------------
    --------------------------------------------
    Toastr Success Code
    --------------------------------------------
    --------------------------------------------*/
    function displayMessage(message) {
        toastr.success(message, 'Event');
    } 
    
</script>
  
</body>
</html>


8 Define a Route

In app/Config/Routes.php, define routes for your FullCalenderController:


use CodeIgniter\Router\RouteCollection;

/**
 * @var RouteCollection $routes
 */
$routes->get('/', 'Home::index');
$routes->get('/fullcalender', 'FullCalenderController::index');
$routes->post('/fullcalenderAjax', 'FullCalenderController::ajax');


9 Folder Structure

10 Run Web Server to Test the App

Start the server using

php spark serve

Access the applicationat http://localhost:8080/fullcalendar/

11 Conclusion

This tutorial explained how to integrate FullCalendar with events in CodeIgniter 4. With features like drag-and-drop and AJAX integration, FullCalendar enhances event management capabilities. Use this CodeIgniter 4 FullCalendar example tutorial as a foundation to customize and extend your application.

Tags