Xem thêm

Mastering JavaScript Resource Calendar: A Comprehensive Tutorial

The JavaScript resource calendar is a powerful web application that displays calendars for multiple resources side by side, providing intuitive drag and drop functionality for creating, moving, and resizing events. Introduction Are you looking to...

javascript resource calendar open source columns The JavaScript resource calendar is a powerful web application that displays calendars for multiple resources side by side, providing intuitive drag and drop functionality for creating, moving, and resizing events.

Introduction

Are you looking to build a dynamic and user-friendly resource calendar for your web application? Look no further! In this tutorial, we will explore the JavaScript resource calendar, a versatile tool that will revolutionize your scheduling tasks. Whether you need to manage tasks, appointments, or bookings, this tutorial will guide you through the process, using PHP and MySQL to implement the backend. So, let's dive in!

Features

The JavaScript resource calendar boasts an array of impressive features, making it the ideal choice for any scheduling project:

  • Display calendars for multiple resources side by side
  • Intuitive drag and drop support for creating, moving, and resizing events
  • Seamless loading of resources (columns) and events via a REST API
  • Robust and efficient backend implemented in PHP/MySQL
  • Leveraging the power of DayPilot Lite for JavaScript, an open-source calendar/scheduler UI library

javascript resource calendar open source columns php mysql database Load resource calendar columns from the MySQL database with ease.

License

The JavaScript resource calendar is licensed under the Apache License 2.0, ensuring that you can leverage its power for both personal and commercial projects.

Resource Calendar: Basic Configuration

Setting up the resource calendar is a breeze. Just follow these simple steps:

  1. Initialize the JavaScript calendar component and set the viewType config property to "Resources".
  2. Define the resource calendar columns using the columns config property.
const dp = new DayPilot.Calendar("dp", {
    viewType: "Resources",
    columns: [
        {id: 1, name: "Person 1"},
        {id: 2, name: "Person 2"},
        {id: 3, name: "Person 3"}
    ]
});
dp.init();

javascript resource calendar open source drag drop event moving Drag and drop events effortlessly with the JavaScript resource calendar.

Loading Columns from MySQL Database

While the static definition of columns may work for simple scenarios, most projects require dynamic column loading from a database. The JavaScript resource calendar simplifies this process:

  1. Utilize the convenience method load to fetch the columns using a REST API call.
  2. Create a custom PHP script that retrieves the required columns from the MySQL database and returns them in the specified JSON format.
require_once '_db.php';

$scheduler_resources = $db->query('SELECT * FROM resources ORDER BY name');

class Resource {}
$resources = array();

foreach($scheduler_resources as $resource) {
    $r = new Resource();
    $r->id = $resource['id'];
    $r->name = $resource['name'];
    $resources[] = $r;
}

header('Content-Type: application/json');
echo json_encode($resources);

Loading Event Data from MySQL Database

Once your resource calendar is initialized and the columns are loaded, it's time to fetch the calendar event data:

  1. Use the events.load method to make a GET HTTP request to retrieve the events.
  2. Implement a PHP script that queries the MySQL database, retrieving events within the visible date range, and returning them in the required JSON format.
require_once '_db.php';

$stmt = $db->prepare('SELECT * FROM events WHERE NOT ((end <= :start) OR (start >= :end))');
$stmt->bindParam(':start', $_GET['start']);
$stmt->bindParam(':end', $_GET['end']);
$stmt->execute();
$result = $stmt->fetchAll();

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'];
    $e->color = $row['color'];
    $e->resource = $row['resource_id'];
    $events[] = $e;
}

header('Content-Type: application/json');
echo json_encode($events);

Resource Calendar: Drag and Drop Event Moving

Adding drag and drop functionality to your resource calendar is a breeze. Follow these steps:

  1. Enable drag and drop operations by default (included in the calendar component).
  2. Implement a custom event handler (onEventMoved) to notify the server about the event move, saving the changes to the MySQL database.
const dp = new DayPilot.Calendar("dp", {
    onEventMoved: async (args) => {
        const params = {
            id: args.e.id(),
            start: args.newStart,
            end: args.newEnd,
            resource: args.newResource
        };

        await DayPilot.Http.post("backend_move.php", params);
    },
    // ...
});

Event Creation using Drag and Drop

Adding new events to your resource calendar using drag and drop is a breeze. Simply add an event handler for onTimeRangeSelected:

  1. Prompt the user to provide the event text through a modal dialog.
  2. Utilize a PHP script to create a new record in the MySQL database.
  3. Add the new event to the resource calendar using the events.add() method.
const dp = new DayPilot.Calendar("dp", {
    onTimeRangeSelected: async (args) => {
        const modal = await DayPilot.Modal.prompt("Create a new event:", "Event 1");
        dp.clearSelection();

        if (modal.canceled) {
            return;
        }

        const params = {
            start: args.start,
            end: args.end,
            text: modal.result,
            resource: args.resource
        };

        const {data} = await DayPilot.Http.post("backend_create.php", params);
        params.id = data.id;
        dp.events.add(params);
    },
    // ...
});

Database Backend (SQLite and MySQL)

By default, the sample project uses SQLite as the backend database. However, switching to MySQL is effortless:

  1. Comment out the _db_sqlite.php include and enable _db_mysql.php.
  2. Update the MySQL connection details in _db_mysql.php.
$host = "127.0.0.1";
$port = 3306;
$username = "username";
$password = "password";
$database = "resource-calendar";
// ...

MySQL Database Schema

The MySQL database schema consists of two tables, events and resources, allowing efficient management of your resource calendar.

CREATE TABLE IF NOT EXISTS `events` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `name` text,
    `start` datetime DEFAULT NULL,
    `end` datetime DEFAULT NULL,
    `color` varchar(30),
    `resource_id` varchar(30) DEFAULT NULL,
    PRIMARY KEY (`id`)
);

CREATE TABLE IF NOT EXISTS `resources` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `name` varchar(200) DEFAULT NULL,
    PRIMARY KEY (`id`)
);

History

Stay up to date with the latest improvements and updates to the JavaScript resource calendar:

  • May 25, 2022: Switched to DayPilot Lite for JavaScript 2022.2.382 (open-source). Using ES6 + async/await syntax.
  • November 21, 2020: Upgraded to DayPilot Pro for JavaScript 2020.4.4766
  • April 19, 2018: Initial release

Now that you have mastered the JavaScript resource calendar, it's time to unleash its power and create dynamic and interactive scheduling experiences. Happy coding!

1