Skip to main content

DHTMLX Booking and Event Calendar. Integration example

Live example​

DHTMLX Booking and DHTMLX Event Calendar cover the two halves of one schedule. The calendar is where staff plan and edit their working time, and Booking is where a visitor takes one of the free slots. This demo runs both over a single REST backend, with a tabbar switching between them. A slot confirmed in Booking is posted to /reservations, which is the endpoint the Client reservations tab of the calendar reads back.

// all dates are specified in UTC
// Check Go backend repository here - https://github.com/DHTMLX/event-calendar-booking-go
const { add, sub, startOfDay, getMinutes, setMinutes, setSeconds, format } = dateFns;
const serverURL = "https://docs.dhtmlx.com/event-calendar-booking-backend";
class CustomDataProvider extends eventCalendar.RestDataProvider {
    send(url, method, data, headers) {
        if (data?.start_date) data.start_date = l2g(roundTimeByStep(data.start_date, 15), true);
        if (data?.end_date) data.end_date = l2g(roundTimeByStep(data.end_date, 15), true);
        return super.send(url, method, data, headers);
    }

    getEvents() {
		return this.send("events", "GET").then(data => {
            for (let i = 0; i < data.length; i++) {
                data[i].start_date = g2l(data[i].start_date);
                data[i].end_date = g2l(data[i].end_date);
            }
		    return data;
        });
	}
}

const restProvider = new CustomDataProvider(serverURL);
const URL = path => serverURL + path;

const weekdayMap = {
    MO: "Monday",
    TU: "Tuesday",
    WE: "Wednesday",
    TH: "Thursday",
    FR: "Friday",
    SA: "Saturday",
    SU: "Sunday"
};

let activeView = "doctors";
let calendarWidget;
let bookingWidget;

// temp. fix
Date.now = () => {
    return g2l(null, true); 
};
      
function roundTimeByStep(date, step) {
	if (!step) return date;
	const minutes = getMinutes(date);
	return setSeconds(setMinutes(date, Math.round(minutes / step) * step), 0);
}

function g2l(v, asDate) {
    const date = v ? new Date(v) : new Date();
    const utcDate = new Date(
        date.getUTCFullYear(),
        date.getUTCMonth(),
        date.getUTCDate(),
        date.getUTCHours(),
        date.getUTCMinutes(),
        date.getUTCSeconds(),
        date.getUTCMilliseconds(),
    );
    return asDate ? utcDate : utcDate.valueOf();
}

function l2g(v, asDate) {
    const date = v ? new Date(v) : new Date();
    const d = Date.UTC(
        date.getFullYear(),
        date.getMonth(),
        date.getDate(),
        date.getHours(),
        date.getMinutes(),
        date.getSeconds(),
        date.getMilliseconds(),
    );
    return asDate ? new Date(d) : d; 
}

function getBookingEndDate(date) {
    date.setFullYear(date.getFullYear() + 2);
    return date;
}

function getID(id) {
	return isNaN(id) ? id : Number(id);
}

function showWarning(text) {
    dhx.message({
        node: "message_container",
        text: text || "Warning",
        css: "dhx_message--warning",
        icon: "dxi-close",
        expire: 3000
    });
}

// event validation
function validate(ev) {
    if (ev.recurring && !ev.start_date_time && !ev.end_date_time) return true;
    const now = g2l();
    if (ev.start_date < now) {
        showWarning("Unable to save/update an event that started in the past");
        return false;
    }
    const hours = (ev.end_date - ev.start_date) / (1000 * 60 * 60);
    if (hours > 16) { 
        showWarning(`The duration of the event must be no more than 16 hours. You have set the duration to ${hours % 1 === 0 ? hours : hours.toFixed(1)} hours.`);
        return false; 
    }
    return true; 
}

// set the active view/initialize the corresponding widget
function setActiveView(id) {
    const views = document.getElementById("views").children;

    for (i = 0; i < views.length; i++) {
        views[i].style.display = views[i].id === id ? "block" : "none";
    }

    activeView = id;

    switch(id) {
        case "booking":
            initBooking();
            break;
        case "clients":
            initClientScheduler();
            break;
        default:
            initDoctorScheduler();
            break;
    }
}

function editEvent(id) {
    calendarWidget.api.exec("edit-event", { id: getID(id) });
}

function closeEventInfo() {
    calendarWidget.api.exec("close-event-info", {});
}

// initialize the main layout
const layout = new dhx.Layout("layout", {
    rows: [
        {
            id: "tabbar",
            height: "content"
        },
        {
            id: "content",
            html: getHTMLTemplate()
        }
    ]
});

const tabbar = new dhx.Tabbar("tabbar", {
    views: [
        { id: "doctors", tab: "Doctor schedule" },
        { id: "clients", tab: "Client reservations" },
        { id: "booking", tab: "Booking" },
    ],
    tabAlign: "center",
    noContent: true,
});

layout.getCell("tabbar").attach(tabbar);
tabbar.events.on("change", id => setActiveView(id));

setActiveView(activeView);

function getHTMLTemplate() {
    return `
        <main id="views" style="width: 100%; height: 100%; background: var(--dhx-background-secondary);">
            <section id="doctors" class="view" style="width: 100%; height: 100%;">
                <div id="doctor_calendar" style="position: relative; z-index: 1; height: 100%; width: 100%; overflow: hidden;"></div>
            </section>
            <section id="clients" class="view" style="width: 100%; height: 100%;">
                <div id="client_calendar" style="position: relative; z-index: 1; height: 100%; width: 100%; overflow: hidden;"></div>
            </section>
            <section id="booking" class="view" style="width: 100%; height: 100%;">
                <div id="booking_root" style="position: relative; z-index: 1; height: 100%; width: 100%; overflow: hidden;"></div>
            </section>
        </main>
    `;
}

function initDoctorScheduler() {
    unloadCSS("https://cdn.svar.dev/fonts/wxi/wx-icons.css");

    if (calendarWidget) calendarWidget.destructor();
    Promise.all([
        restProvider.getCalendars(),
        restProvider.getEvents(),
    ]).then(([doctors, events]) => {
        doctors.forEach(d => {
            d.label = d.name;
        });

        function getDoctor(id) {
            return doctors.find(d => d.id == id);
        }

        function getRepeat(ev) {
            if (ev.recurring) {
                const byday = ev.RRULE.split(";").find(part => part.startsWith("BYDAY"));
                return byday ? byday.split("=")[1] : format(new Date(ev.start_date), "EEEEEE").toUpperCase();
            }

            return "";
        }

        events.forEach(ev => {
            const doctor = getDoctor(ev.type);
            ev.text = doctor.name;
            if (ev.originalStartTime) ev.originalStartTime = new Date(ev.originalStartTime) // bug fix
        });

        const views = [
            {
                id: "timeline",
                label: "Timeline",
                layout: "timeline",
                config: {
                    colsCount: 72,
                    colsWidth: 30,
                    minSectionHeight: 56,
                    eventHeight: 56,
                    key: "type",
                    step: [1, "hour"],
                    header: [
                        { unit: "day", step: 1, format: "EEEE, LLLL d" },
                        { unit: "hour", step: 1, format: "H" },
                    ],
                    sections: doctors,
                    getPrev: date => sub(date, { days: 3 }),
                    getNext: date => add(date, { days: 3 }),
                },
            },
            {
                id: "month",
                label: "Month",
                layout: "month",
            }
        ];

        const config = {
            timeStep: 15,
            viewControl: "dropdown",
            views,
            defaultEditorValues: ev => {
                const doctor = getDoctor(ev.section || ev.type);
                ev.text = doctor.name;
                ev.type = doctor.id;
                return ev;
            },
            dimPastEvents: true,
            editorValidation: event => {
                if (event.RRULE) {
                    const parts = event.RRULE.split(";");
                    if (!parts.includes("FREQ=WEEKLY") || parts.length > 1 && parts.includes("FREQ=WEEKLY") && !parts.includes("INTERVAL=1")) {
                        return "Interval must be set to every 1 week";
                    }
                }
            },
        };

        const editorShape = [ ...eventCalendar.defaultEditorShape ];
        editorShape[0] = editorShape[4];
        editorShape.splice(3, 3);
    
        const locale = { ...eventCalendar.en };
        locale.scheduler = { ...locale.scheduler };
        locale.scheduler.Calendars = "Specialists";
        locale.scheduler["New Event"] = locale.scheduler["Type"] = "Specialist";
        locale.scheduler["Create event"] = "Create shift";
        locale.scheduler["Edit event"] = "Edit";
        locale.scheduler["Delete event"] = "Delete";

        const multieventTemplate = ({ event }) => {
            const start_date = format(event.start_date, "HH:mm");
            const end_date = format(event.end_date, "HH:mm");
            return `
                <div class="multievent-wrapper">
                    <span class="multievent-label">${event.text}</span>
                    <div class="multievent-info">
                        <span>${start_date} - ${end_date}</span>
                        <span> ${getRepeat(event)}</span>
                    </div>
                </div>`;
        };

        const popupTemplate = ({ event, calendar }) => {
            const repeat = getRepeat(event);
            const fullWeekdays = repeat.split(",").map(d => weekdayMap[d] || d).join(", ");

            return `
                <div class="doctor-popup-wrapper">
                    <span>
                        <div class="doctor-popup-header">
                            <div>
                                <span
                                    style="background-color:${calendar.color.border}"
                                    class="doctor-popup-checkbox"></span>
                                <span
                                    class="title">${calendar.label || ''}</span>
                            </div>
                            <i
                                class="wxi-close doctor-popup-close"
                                onclick=closeEventInfo()></i>
                        </div>
                    </span>
                    <div class="doctor-popup-info">
                        <div class="doctor-popup-name">${event.text}</div>
                        <div class="doctor-popup-date">
                            ${format(event.start_date, "MMM, do HH:mm")}
                            -
                            ${format(event.end_date, "HH:mm")}
                        </div>
                        ${fullWeekdays ? `<div class="doctor-popup-repeat">Repeating every: ${fullWeekdays}</div>` : ""}
                        <div class="doctor-popup-controls">
                            <i
                                class="wxi-edit doctor-popup-control"
                                onclick=editEvent('${event.id}')><span
                                    class="doctor-popup-label">Edit event</span></i>
                        </div>
                    </div>
                </div>
            `;
        };

        calendarWidget = new eventCalendar.EventCalendar("#doctor_calendar", {
            locale,
            editorShape,
            events,
            calendars: doctors,
            config,
            mode: "timeline",
            date: g2l(null, true),
            templates: {
                multievent: multieventTemplate,
                popup: popupTemplate
            }
        });

        calendarWidget.api.setNext(restProvider);

        calendarWidget.api.intercept("add-event", ({ event }) => {
            const doctor = getDoctor(event.type);
            event.text = doctor.name;
            return validate(event);
        });

        calendarWidget.api.intercept("update-event", ({ event }) => {
            const doctor = getDoctor(event.type);
            event.text = doctor.name;
            return validate(event);
        });

        // restricting custom patterns to weekly
        calendarWidget.api.on("edit-event", () => {
            setTimeout(() => {
                const formContainer = document.querySelector(".wx-event-calendar-editor-form");
                const recurringSelect = document.querySelector(".wx-event-calendar-recurring-wrapper select");
                if (!recurringSelect) return;

                const handleChange = () => {
                    if (recurringSelect.value === "CUSTOM") {
                        formContainer.querySelector(".wx-event-calendar-recurring-wrapper input").readOnly = true;

                        const customSelect = formContainer.querySelector(".wx-event-calendar-flex-col select");
                        if (customSelect) {
                            customSelect.value = "WEEKLY";
                            customSelect.dispatchEvent(new Event("change", { bubbles: true }));
                        }
                    }
                };

                recurringSelect.addEventListener("change", handleChange);
            }, 0);
        });
    });
}

function initClientScheduler() {
    unloadCSS("https://cdn.svar.dev/fonts/wxi/wx-icons.css");

    if (calendarWidget) calendarWidget.destructor();
    Promise.all([
        fetch(URL("/calendars")),
        fetch(URL("/reservations")),
    ]).
    then(responses => Promise.all(responses.map(response => response.json())))
    .then(([doctors, events]) => {
        doctors.forEach(d => {
            d.label = d.name;
        });

        function getDoctor(id) {
            return doctors.find(d => d.id == id);
        }

        events.forEach(e => {
            const doctor = getDoctor(e.type);

            e.text = e.client_name;
            e.email = e.client_email;
            e.details = e.client_details;
            e.start_date = g2l(e.date);
            e.end_date = g2l(e.date + doctor.slot_size * 60 * 1000);
        });

        const views = [
            {
                id: "day",
                label: "Day",
                layout: "day",
            },
            {
                id: "week",
                label: "Week",
                layout: "week",
            },
            {
                id: "month",
                label: "Month",
                layout: "month",
            }
        ];

        const config = {
            viewControl: "dropdown",
            views,
            createEventOnDblClick: false,
            dimPastEvents: true,
            dragCreate: false,
            readonly: true
        };

        const weekEventTemplate = ({ event }) => {
            const start_date = format(event.start_date, "HH:mm");
            return `
                <div class="week-event-wrapper">
                    <div class="week-event-info">
                        <span>${event.text}</span>
                        <span>${start_date}</span>
                    </div>
                </div>`;
        };

        const popupTemplate = ({ event, calendar }) => {
            const doctor = getDoctor(event.type);
            return `
                <div class="client-popup-wrapper">
                    <span>
                        <div class="client-popup-header">
                            <h1 style="color: ${calendar.color.border}">${event.text}</h1>
                            <i class="wxi-close wx-event-calendar-close" onclick=closeEventInfo()></i>
                        </div>	
                    </span>
                    <div class="client-popup-info">
                        <h2>Assignee: ${doctor.name}</h2>
                        <div>Email: ${event.email}</div>
                        <div>Details: ${event.details || "-"}</div>
                        <br>
                        <div>
                            ${format(event.start_date, "MMM, do HH:mm")}
                            -
                            ${format(event.end_date, "HH:mm")}
                        </div>
                    </div>
                </div>
            `;
        };

        const locale = {...eventCalendar.en};
        locale.scheduler = {...locale.scheduler};
        locale.scheduler.Calendars = "Specialists";

        calendarWidget = new eventCalendar.EventCalendar("#client_calendar", {
          	locale,
            calendars: doctors,
            events,
            config,
            mode: "week",
            date: g2l(null, true),
            templates: {
                weekEvent: weekEventTemplate,
                popup: popupTemplate
            }
        });
    });
}

function initBooking() {
    unloadCSS("https://cdn.dhtmlx.com/fonts/wxi/wx-icons.css");

    const handleSlotReservation = event => {
        const { confirm, slot, data } = event;

        const info = {
            doctor: slot.id,
            date: l2g(slot.time[0]),
            form: {
                name: data.name,
                email: data.email,
                details: data.description, 
            },
        };

        fetch(URL("/reservations"), {
            method: "POST",
            body: JSON.stringify(info),
        }).then(response => {
            if (response.ok) confirm.done();
            else confirm.error();
        });
    };

    if (bookingWidget) bookingWidget.destructor();

    bookingWidget = new booking.Booking("#booking_root", {
		data: [],
		start: g2l(null, true),
		end: getBookingEndDate(g2l(null, true))
    });

    fetch(URL("/units"))
        .then(res => res.json())
        .then(units => {
            units.forEach(unit => {
                if (unit.usedSlots) unit.usedSlots = unit.usedSlots.map(g2l);
                if (unit.slots) {
                    unit.slots = unit.slots.map(slot => {
                        if (slot.dates) {
                            return {
                                ...slot,
                                dates: slot.dates.map(g2l)
                            };
                        }
                        return slot;
                    });
                };
            });

            bookingWidget.setConfig({ data: units });
            bookingWidget.setConfirmHandler(handleSlotReservation);
        });
}
<script src="https://cdn.jsdelivr.net/npm/date-fns@4.1.0/cdn.min.js"></script>

<!-- component container -->
<div id="layout" style="height: 100%;"></div>

<style>
* {
        --wx-event-calendar_hour-cell-height: 150px;
    }
    #doctor_calendar .window .group {
        flex-direction: column;
    }
    #doctor_calendar .window .group .group-item:nth-child(2) {
        display: none !important;
    }
    select option[value="DAILY"], select option[value="MONTHLY"], select option[value="YEARLY"], select option[value="WORKDAYS"] {
        display: none;
    }
    .doctor-popup-info {
		width: 300px;
		display: flex;
		flex-direction: column;
	}
	.doctor-popup-checkbox {
		display: inline-block;
		width: 9px;
		height: 9px;
		border-radius: 2px;
		margin-right: 4px;
	}
	.doctor-popup-name {
		font-size: var(--wx-font-size-md);
		font-weight: var(--wx-font-weight-md);
		margin: 5px 0;
	}
	.doctor-popup-date {
		text-transform: capitalize;
	}
	.doctor-popup-controls {
		margin-top: 7px;
		display: flex;
		gap: 8px;
	}
	.doctor-popup-control {
		display: flex;
		align-items: center;
		gap: 4px;
		cursor: pointer;
		font-style: normal;
		color: var(--wx-color-primary);
	}
	.doctor-popup-label {
		color: var(--wx-color-font);
	}
	.doctor-popup-wrapper {
		padding: 10px 20px 15px 20px;
		max-width: 500px;
		font-family: var(--wx-font-family);
		line-height: var(--wx-line-height);
		line-height: var(--wx-line-height-md);
	}
	.doctor-popup-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		cursor: default;
	}
	.doctor-popup-close {
		cursor: pointer;
		color: var(--wx-icon-color);
		font-size: var(--wx-font-size-md);
	}
	.doctor-popup-title {
		font-size: var(--wx-font-size-sm);
	}
    #client_calendar .wx-event-calendar-toolbar [data-id="add"] {
        display: none;
    }
    #client_calendar .wx-event-calendar-readonly i.wx-readonly-day-event {
        display: none;
    }
    .client-popup-wrapper {
		padding: 10px 20px 15px 20px;
		max-width: 500px;
	}
    .client-popup-wrapper i {
        cursor: pointer;
    }
    .client-popup-wrapper h1 {
        margin: 5px 0;
    }
    .client-popup-wrapper h2 {
        font-size: 16px;
    }
    .client-popup-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
	.client-popup-info {
		width: 280px;
		display: flex;
		flex-direction: column;
	}
    .multievent-wrapper {
        width: 100%;
    }
    .multievent-info {
        display: flex;
        justify-content: space-between;
    }
    .week-event-info {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        gap: 4px;
    }
    .wx-event-calendar-title [data-id="add-calendar"],
    .wx-event-calendar-calendars-list .wxi-dots-v {
		display: none !important; 
    }
    .wx-event-calendar-time-line-wrapper-vertical,
    .wx-event-calendar-time-line-wrapper-horizontal {
        display: none !important;
    }
</style>

<script>
function unloadCSS(href) {
        let link = document.querySelector(`link[href="${href}"]`);
        if (link) link.remove();
    }
</script>

Use case​

Scheduling products almost always have two audiences. Staff need a grid they can drag, with recurring shifts, validation, and an editor, while a visitor needs one question answered: when can I come in. Building both on one backend keeps the two views honest, because the free slots a visitor sees are the working time somebody actually planned. The split also lets each side keep its own rules. On the staff side this demo caps a shift at 16 hours and refuses past dates. The visitor gets a plain card list with no editing at all.

How to do this in your app​

  • Point both widgets at one service: the demo uses the Go project event-calendar-booking-go, where /calendars and /events feed the calendar, /units feeds Booking, and /reservations holds what was booked.
  • Load Booking after the frame: create it with data: [], fetch /units, then call setConfig({ data: units }) and setConfirmHandler(handleSlotReservation).
  • Post in the shape the backend expects: the handler builds { doctor: slot.id, date: l2g(slot.time[0]), form: { name, email, details } } and sends it to /reservations.
  • Convert the timestamps on both sides: the backend stores UTC, so g2l runs on everything loaded and l2g on everything sent.
  • Rebuild on a tab switch: the demo calls bookingWidget.destructor() before creating the widget again, and the calendar does the same.

Good to know​

  • Each calendar tab reads its own feed: the staff tab is a timeline of shifts from /events, with an editor and recurring shifts, and the Client reservations tab is the same calendar configured with readonly: true, reading /reservations.
  • Each widget keeps its own configuration: the calendar has its editor shape and locale, Booking has its slots, filter, and dialog, and neither reads the other's settings.
  • The link between them is the server: nothing is shared in the browser, so the same pattern works when the two views live in separate applications.

FAQ​

Can DHTMLX Booking and Event Calendar work with the same data?​

Yes, through a common backend. Each widget loads what it needs from its own endpoints, and the reservations one writes are the events the other displays.

How does a confirmed booking reach the calendar?​

setConfirmHandler posts the slot and the form to the reservations endpoint. The calendar then reads that endpoint and renders each reservation, converting the stored start into a start and end pair.

Do the two widgets have to be on one page?​

No. They talk to the server rather than to each other, so the staff view and the visitor view can be separate applications with separate deployments.

API reference​

Additional resources​