This tutorial shows how to create an interactive event calendar in JavaScript using the event calendar widget from DayPilot Pro for JavaScript package. It includes a sample PHP project with an SQLite database. The event calendar supports drag and drop operations (event creating, moving and resizing), switching daily and weekly view and is styled using a CSS theme.

Included

Requirements

  • PHP 5

See Also

Features

  • JavaScript event calendar widget
  • Switching day and week view
  • Drag and drop support (event creating, moving, resizing)
  • PHP backend
  • Sample database (SQLite)
  • Full CSS styling (themes)
  • HTML5 support

License

Licensed for testing and evaluation purposes. Please see the license agreement included in the sample project. You can use the source code of the tutorial if you are a licensed user of DayPilot Pro for JavaScript. Buy a license.

Event Calendar Setup

Include daypilot-all.min.js script:

<script src="js/daypilot/daypilot-all.min.js" type="text/javascript"></script>

Add the event calendar widget placeholder:

<div id="dp"></div>

Add the event calendar initialization code:

var dp = new DayPilot.Calendar("dp");
dp.init();

This will display the event calendar with default configuration. It will be a day view

CSS Theme

javascript-event-calendar-php-css.png

Apply a CSS theme using .cssClassPrefix property:

var dp = new DayPilot.Calendar("dp");
dp.cssClassPrefix = "calendar_white";
dp.init();

Don't forget to include the theme CSS stylesheet:

<link type="text/css" rel="stylesheet" href="themes/calendar_white.css" />

You can create your own CSS theme using the online theme designer.

Visible Date

Set the visible date using .startDate property

dp.startDate = new DayPilot.Date("2013-05-01");  // or just dp.startDate = "2013-05-01";

Load Events

We will load the events after the initialization is complete using .events.add() method:

function loadEvents() {
    DayPilot.request("backend_events.php", function(result) {
        var data = eval("(" + result.responseText + ")");
        for(var i = 0; i < data.length; i++) {
            var e = new DayPilot.Event(data[i]);                
            dp.events.add(e);
        }
    });
}

backend_events.php

<?php
require_once '_db.php';
    
$result = $db->query('SELECT * FROM events');

class Event {}
$events = array();

foreach($result as $row) {
  $e = new Event();
  $e->id = $row['id'];
  $e->text = $row['name'];
  $e->start = $row['start'];
  $e->end = $row['end'];
  $events[] = $e;
}

echo json_encode($events);

?>

Weekly Event Calendar View

javascript-event-calendar-php-week.png

You can switch the event calendar to week view using .viewType property:

<a href="javascript:dp.viewType='Week';dp.update();">Week</a>

Daily Event Calendar View

javascript-event-calendar-php-day.png

You can switch the event calendar to day view by setting viewType property to "Day".

<a href="javascript:dp.viewType='Day';dp.update();">Day</a>

Drag and Drop Event Moving

javascript-event-calendar-php-move.png

Drag and drop event moving is enabled by default. Weed need to add a custom handler that will save the changes in a database on the server side using PHP.

dp.onEventMoved = function (args) {
    DayPilot.request(
        "backend_move.php", 
        function(req) { // success
            var response = eval("(" + req.responseText + ")");
            if (response && response.result) {
                dp.message("Moved: " + response.message);
            }
        },
        args,
        function(req) {  // error
            dp.message("Saving failed");
        }
    );        
};

backend_move.php

<?php
require_once '_db.php';

$insert = "UPDATE events SET start = :start, end = :end WHERE id = :id";

$stmt = $db->prepare($insert);

$stmt->bindParam(':start', $start);
$stmt->bindParam(':end', $end);
$stmt->bindParam(':id', $id);

$received = json_decode(file_get_contents('php://input'));

$id = $received->e->id;
$start = $received->newStart;
$end = $received->newEnd;
$stmt->execute();

class Result {}

$response = new Result();
$response->result = 'OK';
$response->message = 'Update successful';

echo json_encode($response);

?>

Drag and Drop Event Resizing

javascript-event-calendar-php-resize.png

The calendar event resizing handler is very similar:

dp.onEventResized = function (args) {
    DayPilot.request(
        "backend_resize.php", 
        function(req) { // success
            var response = eval("(" + req.responseText + ")");
            if (response && response.result) {
                dp.message("Resized: " + response.message);
            }
        },
        args,
        function(req) {  // error
            dp.message("Saving failed");
        }
    );    
};

backend_resize.php

<?php
require_once '_db.php';

$insert = "UPDATE events SET start = :start, end = :end WHERE id = :id";

$stmt = $db->prepare($insert);

$stmt->bindParam(':start', $start);
$stmt->bindParam(':end', $end);
$stmt->bindParam(':id', $id);

$received = json_decode(file_get_contents('php://input'));

$id = $received->e->id;
$start = $received->newStart;
$end = $received->newEnd;
$stmt->execute();

class Result {}

$response = new Result();
$response->result = 'OK';
$response->message = 'Update successful';

echo json_encode($response);

?>

Drag and Drop Event Creating

javascript-event-calendar-php-create.png

dp.onTimeRangeSelected = function (args) {
    var name = prompt("New event name:", "Event");
    dp.clearSelection();
    if (!name) return;
    var e = new DayPilot.Event({
        start: args.start,
        end: args.end,
        id: DayPilot.guid(),
        text: name
    });
    dp.events.add(e);

    args.text = name;

    DayPilot.request(
        "backend_create.php", 
        function(req) { // success
            var response = eval("(" + req.responseText + ")");
            if (response && response.result) {
                dp.message("Created: " + response.message);
            }
        },
        args,
        function(req) {  // error
            dp.message("Saving failed");
        }
    ); 
};

backend_create.php

<?php
require_once '_db.php';

$insert = "INSERT INTO events (name, start, end) VALUES (:name, :start, :end)";

$stmt = $db->prepare($insert);

$stmt->bindParam(':start', $start);
$stmt->bindParam(':end', $end);
$stmt->bindParam(':name', $name);

$received = json_decode(file_get_contents('php://input'));

$start = $received->start;
$end = $received->end;
$name = $received->text;
$stmt->execute();

class Result {}

$response = new Result();
$response->result = 'OK';
$response->message = 'Created with id: '.$db->lastInsertId();

echo json_encode($response);

?>

Highlighting Weekends

You can highlight the weekend cells using onBeforeCellRender event:

dp.onBeforeCellRender = function(args) {
    if (args.cell.start.getDayOfWeek() === 6 || args.cell.start.getDayOfWeek() === 0) {
        args.cell.backColor = "#eee";
    }
};

Highlighting Lunch Break

dp.onBeforeCellRender = function(args) {
  if (args.cell.start.getHours() === 13) {
    args.cell.backColor = "#eee";
  }
};