DHTMLX Booking and Scheduler. Integration example
Live example
DHTMLX Scheduler is the widget behind both staff tabs. Doctor schedule is where staff plan working time, with drag and drop, recurring shifts, and an editor, and those shifts are saved through Scheduler's DataProcessor in REST-JSON mode. Client reservations is Scheduler again, opened as a read-only units view of the bookings. DHTMLX Booking is where a visitor takes a free slot. Each confirmed slot is posted to /doctors/reservations, and that is the feed the Client reservations tab loads.
// all dates are specified in UTC
// Check Go backend repository here - https://github.com/DHTMLX/scheduler-booking-go
const serverURL = "https://docs.dhtmlx.com/scheduler-booking-backend";
const URL = path => {
return serverURL + path;
};
const schedulerHeader = [
"today",
"prev",
"next",
"date",
"spacer",
{
view: "minicalendar",
click: showCalendar
}
];
const weekdayMap = {
MO: "Monday",
TU: "Tuesday",
WE: "Wednesday",
TH: "Thursday",
FR: "Friday",
SA: "Saturday",
SU: "Sunday"
};
let activeView = "doctors";
let schedulerWidget;
let bookingWidget;
let dp;
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);
date.setHours(23, 59, 59, 999);
return date;
}
// event validation
function validate(ev, original) {
const now = g2l();
if (original && original.start_date < now) {
scheduler.alert("Unable to update an event that has expired");
return false;
}
if (+ev.start_date < now) {
// fix for past recurrings
const modal = document.querySelector(".scheduler_modal_box");
if (modal && (String(ev.id).includes("#") || ev.recurring_event_id)) {
modal.querySelector("[aria-label='Cancel']").click();
}
scheduler.alert(
"Unable to save an event that started in the past"
);
return false;
}
const hours = ev.rrule ? ev.duration / (60 * 60) : (ev.end_date - ev.start_date) / (1000 * 60 * 60);
if (hours > 16) {
scheduler.alert(
`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;
}
function showCalendar() {
const pos = this.getBoundingClientRect();
if (schedulerWidget.isCalendarVisible()) {
schedulerWidget.destroyCalendar();
} else {
schedulerWidget.renderCalendar({
position: { left: pos.x - 240, top: pos.y + 20 },
date: schedulerWidget.getState().date,
navigation: true,
handler: function (date, calendar) {
schedulerWidget.setCurrentView(date);
schedulerWidget.destroyCalendar();
}
});
}
};
function setEvents(scheduler) {
scheduler.attachEvent(
"onBeforeEventChanged",
(ev, e, is_new, original) => {
return validate(ev, original);
}
);
scheduler.attachEvent("onBeforeEventDelete", (id, ev) => {
if (+ev.start_date < g2l()) {
scheduler.alert(
"Cannot delete an event that has expired"
);
return false;
}
return true;
});
scheduler.attachEvent("onEventSave", (id, ev) => {
return validate(ev);
});
}
function setDataProcessor(scheduler) {
const dp = new scheduler.DataProcessor(URL("/doctors/worktime"));
dp.init(scheduler);
dp.setTransactionMode("REST-JSON");
dp.attachEvent("onBeforeUpdate", (id, state, data) => {
data.doctor_id = parseInt(data.doctor_id);
if (data.recurring_event_id) data.recurring_event_id = String(data.recurring_event_id);
if (data.rrule && typeof data.deleted === "undefined") data.deleted = null;
return true;
});
dp.attachEvent("onAfterUpdate", (id, action, tid, response) => {
if (id != response.id) {
scheduler.changeEventId(id, response.id);
scheduler.render();
}
});
return dp;
}
// set the active view/initialize the corresponding widget
function setActiveView(id) {
const views = document.getElementById("views").children;
for (let 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;
}
}
// 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_scheduler"
class="dhx_cal_container"
style="width: 100%; height: 100%"
>
</div>
</section>
<section id="clients" class="view" style="width: 100%; height: 100%;">
<div
id="client_scheduler"
class="dhx_cal_container"
style="width: 100%; height: 100%"
>
</div>
</section>
<section id="booking" class="view" style="width: 100%; height: 100%;">
<div id="root" style="position: relative; z-index: 1; height: 100%; width: 100%; overflow: hidden;"></div>
</section>
</main>
`;
}
function initDoctorScheduler() {
if (schedulerWidget) schedulerWidget.destructor();
const scheduler = Scheduler.getSchedulerInstance();
schedulerWidget = scheduler;
schedulerWidget.ajax.get(URL("/doctors")).then(req => {
if (schedulerWidget !== scheduler) return;
const doctors = JSON.parse(req.response);
doctors.forEach((d, index) => {
d.label = d.name;
d.key = d.id;
d.index = index;
});
function getDoctor(id) {
return doctors.find(d => d.id == id);
}
function getRepeat(ev) {
if (String(ev.id).includes("#")) {
const series = schedulerWidget.getEvent(ev.id.split("#")[0]);
const byday = series.rrule.split(";").find(part => part.startsWith("BYDAY"));
if (byday) return byday.split("=")[1];
}
}
const doctorSubrowHeight = 25;
schedulerWidget.plugins({
timeline: true,
daytimeline: true,
recurring: true,
tooltip: true,
minical: true
});
schedulerWidget.locale.labels.timeline_tab = "Timeline";
schedulerWidget.locale.labels.section_doctor = "Doctor";
schedulerWidget.config.details_on_create = true;
schedulerWidget.config.details_on_dblclick = true;
schedulerWidget.config.undo_deleted = false;
const tHeader = [ ...schedulerHeader ];
tHeader.splice(5, 0, ...[ "timeline", "month" ]);
schedulerWidget.config.header = tHeader;
schedulerWidget.createTimelineView({
name: "timeline",
x_unit: "minute",
x_date: "%H:%i",
x_step: 60,
x_size: 24,
x_start: 0,
y_property: "doctor_id",
dx: 220,
dy: doctors.length * 25,
event_dy: doctorSubrowHeight,
render: "days",
days: 7,
scrollable: true,
column_width: 50,
cell_template: true,
getEventTop: event => {
const doctor = getDoctor(event.doctor_id);
return doctor ? doctor.index * doctorSubrowHeight : 0;
}
});
// custom form for recurring events
schedulerWidget.form_blocks.recurring.render = () => {
const loc = schedulerWidget.locale.labels;
return `<div class="dhx_form_rrule">
<div class="dhx_form_repeat_pattern">
<select>
<option value="NEVER">${loc.repeat_never}</option>
<option value="WEEKLY">${loc.repeat_weekly}</option>
<option value="CUSTOM">${loc.repeat_custom}</option>
</select>
</div>
<div class="dhx_form_repeat_custom dhx_hidden">
<div class="dhx_form_repeat_custom_interval dhx_hidden">
<input name="repeat_interval_value" type="number" readonly min="1" max="1">
<select name="repeat_interval_unit">
<option value="WEEKLY">${loc.repeat_freq_week}</option>
</select>
</div>
<label>${loc.repeat_weekly}</label>
<div class="dhx_form_repeat_custom_additional">
<div class="dhx_form_repeat_custom_week">
<label><input class="dhx_repeat_checkbox" type="checkbox" name="week_day" value="MO" />${loc.day_for_recurring[1]}</label>
<label><input class="dhx_repeat_checkbox" type="checkbox" name="week_day" value="TU" />${loc.day_for_recurring[2]}</label>
<label><input class="dhx_repeat_checkbox" type="checkbox" name="week_day" value="WE" />${loc.day_for_recurring[3]}</label>
<label><input class="dhx_repeat_checkbox" type="checkbox" name="week_day" value="TH" />${loc.day_for_recurring[4]}</label>
<label><input class="dhx_repeat_checkbox" type="checkbox" name="week_day" value="FR" />${loc.day_for_recurring[5]}</label>
<label><input class="dhx_repeat_checkbox" type="checkbox" name="week_day" value="SA" />${loc.day_for_recurring[6]}</label>
<label><input class="dhx_repeat_checkbox" type="checkbox" name="week_day" value="SU" />${loc.day_for_recurring[0]}</label>
</div>
<div class="dhx_form_repeat_custom_month dhx_hidden">
<select name="dhx_custom_month_option">
<option value="month_date"></option>
<option value="month_nth_weekday"></option>
</select>
</div>
<div class="dhx_form_repeat_custom_year dhx_hidden">
<select name="dhx_custom_year_option">
<option value="month_date"></option>
<option value="month_nth_weekday"></option>
</select>
</div>
</div>
<div class="dhx_form_repeat_ends dhx_hidden">
<div>${loc.repeat_ends}</div>
<div class="dhx_form_repeat_ends_options">
<select name="dhx_custom_repeat_ends">
<option value="NEVER">${loc.repeat_never}</option>
<option value="AFTER">${loc.repeat_radio_end2}</option>
<option value="ON">${loc.repeat_on_date}</option>
</select>
<div class="dhx_form_repeat_ends_extra">
<div class="dhx_form_repeat_ends_after dhx_hidden">
<label><input type="number" min="1" name="dhx_form_repeat_ends_after">${loc.repeat_text_occurences_count}</label>
</div>
<div class="dhx_form_repeat_ends_on dhx_hidden">
<input type="date" name="dhx_form_repeat_ends_ondate">
</div>
</div>
</div>
</div>
</div>
</div>`;
};
schedulerWidget.config.lightbox.sections = [
{
name: "doctor",
height: 30,
type: "select",
options: doctors,
map_to: "doctor_id",
},
{ name: "recurring", height: 115, type: "recurring", map_to: "rec_type" },
{ name: "time", height: 72, type: "time", map_to: "auto" },
];
schedulerWidget.templates.timeline_cell_value = (evs, date, section) => {
const sectionDate = new Date(section.key);
sectionDate.setHours(date.getHours());
const className = sectionDate.valueOf() < g2l() ? "past-cell" : "";
return doctors.map(d => `<div class="timeline-section-doctor-subrow ${className}" data-doctor-id="${d.id}"></div>`).join("");
};
schedulerWidget.templates.event_class = (start, end, ev) => {
const event = schedulerWidget.getEvent(ev.id);
if (event.start_date.valueOf() < g2l()) return "past-event";
};
const hourToStr = schedulerWidget.date.date_to_str(schedulerWidget.config.hour_date);
schedulerWidget.templates.event_bar_text = (start, end, ev) => {
const doctor = getDoctor(ev.doctor_id);
const repeat = getRepeat(ev) ? "<span style='margin-left:auto;padding-left:5px;'>" + getRepeat(ev) + "</span>" : "";
return `${doctor ? doctor.name : ev.text}, ${hourToStr(start)} - ${hourToStr(end)}${repeat}`;
};
schedulerWidget.templates.tooltip_text = (start, end, ev) => {
const repeat = getRepeat(ev);
let tooltip = `<b>Doctor:</b> ${getDoctor(ev.doctor_id).name}
<br/><b>Start date:</b> ${schedulerWidget.templates.tooltip_date_format(start)}
<br/><b>End date:</b> ${schedulerWidget.templates.tooltip_date_format(end)}`;
if (repeat) {
const fullWeekdays = repeat.split(",").map(d => weekdayMap[d] || d).join(", ");
tooltip += `<br/><b>Repeating every:</b> ${fullWeekdays}`;
}
return tooltip;
};
const dateToStr = schedulerWidget.date.date_to_str("%F %j");
const weekDayToStr = schedulerWidget.date.date_to_str("%l");
const doctorNameToStr = d => {
const parts = d.label.split(" ");
return parts[1] || d.label;
}
schedulerWidget.templates["timeline_scale_label"] = (
section_id,
section_label,
section_options
) => {
return `<div class="timeline-section-label">
<div class="timeline-section-day">
<div>${weekDayToStr(section_label)}</div>
<div>${dateToStr(section_label)}</div>
</div>
<div class="timeline-section-subrows">
${doctors.map(d => `<div class="timeline-section-doctor-subrow">${doctorNameToStr(d)}</div>`).join("")}
</div>
</div>`;
};
schedulerWidget.attachEvent("onBeforeDrag", (id, mode, e) => {
const now = g2l();
if (e.target.classList.contains("dhx_cal_event_line")) {
const ev = schedulerWidget.getEvent(id);
if (ev.start_date.valueOf() < now) return false;
} else {
const mousePosition = schedulerWidget.getActionData(e);
if (mousePosition.date.valueOf() < now) return false;
}
return true;
});
schedulerWidget.attachEvent("onEventCreated", (id, e) => {
const doctorCell = e.target.closest("[data-doctor-id]");
if (doctorCell) schedulerWidget.getEvent(id).doctor_id = doctorCell.getAttribute("data-doctor-id");
});
schedulerWidget.init("doctor_scheduler", g2l(null, true), "timeline");
setEvents(schedulerWidget);
schedulerWidget.load(URL("/doctors/worktime"));
if (dp) dp.destructor();
dp = setDataProcessor(schedulerWidget);
});
}
function initClientScheduler() {
if (schedulerWidget) schedulerWidget.destructor();
const scheduler = Scheduler.getSchedulerInstance();
schedulerWidget = scheduler;
Promise.all([
schedulerWidget.ajax.get(URL("/doctors")),
schedulerWidget.ajax.get(URL("/doctors/reservations")),
]).then(([doctorsReq, eventsReq]) => {
if (schedulerWidget !== scheduler) return;
const doctors = JSON.parse(doctorsReq.response);
doctors.forEach(d => {
d.label = d.name;
d.key = d.id;
});
function getDoctor(id) {
return doctors.find(d => d.id == id);
}
let events = JSON.parse(eventsReq.response);
events.forEach(e => {
e.date = g2l(e.date);
e.start_date = new Date(e.date);
const doctor = getDoctor(e.doctor_id);
e.end_date = e.date + doctor.slot_size * 60 * 1000;
});
schedulerWidget.plugins({
units: true,
readonly: true,
minical: true,
quick_info: true,
});
schedulerWidget.locale.labels.week_unit_tab = "Unit";
schedulerWidget.locale.labels.section_doctor = "Doctor";
schedulerWidget.locale.labels.section_client = "Client";
schedulerWidget.locale.labels.section_email = "Email";
schedulerWidget.locale.labels.section_details = "Details";
schedulerWidget.config.separate_short_events = true;
schedulerWidget.config.hour_size_px = 88;
schedulerWidget.xy.scale_height = 120;
schedulerWidget.config.icons_select = [];
const tHeader = [ ...schedulerHeader ];
tHeader.splice(5, 0, ...[ "week_unit", "week", "month" ]);
schedulerWidget.config.header = tHeader;
schedulerWidget.createUnitsView({
name: "week_unit",
property: "doctor_id",
list: doctors,
days: 3,
});
schedulerWidget.templates.event_bar_text = (start, end, event) => event.client_name;
schedulerWidget.templates.quick_info_title = (start, end, ev) => ev.client_name;
schedulerWidget.templates.quick_info_content = (start, end, ev) => {
return `
<br><b>Assignee:</b> ${getDoctor(ev.doctor_id).name}
<br><b>Email:</b> ${ev.client_email}
<br><b>Details:</b> ${ev.client_details || "-"}
`;
};
schedulerWidget.templates.quick_info_date = (start, end, ev) => {
return `${schedulerWidget.templates.day_date(start)} ${schedulerWidget.templates.event_date(start)} –
${schedulerWidget.templates.day_date(end)} ${schedulerWidget.templates.event_date(end)}`
}
schedulerWidget.templates.week_unit_scale_text = (key, label, unit, date) => {
return `<div style="position:absolute;width: 74px;line-height: 12px;transform: translateY(30px) rotate(90deg);">${label}</div>`;
};
schedulerWidget.config.multi_day = true;
schedulerWidget.templates.event_text = (s, e, ev) => ev.client_name;
schedulerWidget.init("client_scheduler", g2l(null, true), "week_unit");
// block all modifications
schedulerWidget.attachEvent("onBeforeDrag", () => false);
schedulerWidget.attachEvent("onClick", () => false);
schedulerWidget.attachEvent("onBeforeLightbox", () => false);
schedulerWidget.config.dblclick_create = false;
schedulerWidget.parse(events);
});
}
function initBooking() {
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("/doctors/reservations"), {
method: "POST",
body: JSON.stringify(info),
}).then(response => {
if (response.ok) confirm.done();
else confirm.error();
});
};
if (bookingWidget) bookingWidget.destructor();
const widget = new booking.Booking("#root", {
data: [],
start: g2l(null, true),
end: getBookingEndDate(g2l(null, true))
});
bookingWidget = widget;
fetch(URL("/units"))
.then(res => res.json())
.then(units => {
if (bookingWidget !== widget) return;
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;
});
};
});
widget.setConfig({ data: units });
widget.setConfirmHandler(handleSlotReservation);
});
}
<!-- component container -->
<div id="layout" style="height: 100%;"></div>
<style>
#client_scheduler .dhx_event_resize {
display: none;
}
#client_scheduler .dhx_cal_quick_info {
width: 320px;
}
#client_scheduler .dhx_cal_qi_content {
padding-top: 8px;
}
#client_scheduler.dhx_scheduler_week_unit .dhx_cal_header {
height: 114px !important;
}
#client_scheduler.dhx_scheduler_week_unit .dhx_scale_bar:not(.dhx_second_scale_bar) {
height: 90px !important;
}
#client_scheduler .dhx_cal_tab_segmented[name="week_tab"] {
border-left-style: solid;
border-radius: var(--dhx-scheduler-border-radius) 0px 0px var(--dhx-scheduler-border-radius);
}
.timeline-section-day {
border-right: var(--dhx-scheduler-default-border);
padding:8px;
flex-shrink:0;
width: 100px;
display: flex;
flex-direction: column;
line-height: 120% !important;
justify-content: center;
align-items: flex-start;
gap: 12px;
}
.timeline-section-label {
--subrow-border-color: #eee;
display: flex;
}
.timeline-section-subrows {
flex: 1;
}
.timeline-section-doctor-subrow {
height: 25px !important;
line-height: 25px !important;
--subrow-border-color: #eee;
border-bottom: 1px solid var(--subrow-border-color);
}
.timeline-section-doctor-subrow:last-child {
border-bottom: none;
}
.past-cell {
background: #D2D2D280;
--subrow-border-color: #DCDCDC !important;
}
.past-event {
opacity: 0.6;
}
.past-event .dhx_event_resize {
display: none !important;
}
.dhx_edit_recurrence_options label:nth-child(2):not(:last-child) {
display: none !important;
}
</style>Use case
Many teams already run Scheduler in the back office and only later need a page their visitors can use. Rebuilding the planning grid for that audience would be wrong twice over, since visitors do not want a grid and staff do not want a card list. Adding Booking on the same backend gives each side the interface it needs and keeps one source of availability. Both staff screens stay on Scheduler. Doctor schedule edits the shifts, and Client reservations shows what was booked. The staff rules stay on the doctor tab: this demo refuses shifts in the past, blocks anything over 16 hours, and protects expired entries from deletion.
How to do this in your app
- Keep one service behind both widgets: the demo uses the Go project
scheduler-booking-go.GET /doctorsfills both Scheduler tabs,/doctors/worktimeholds the shifts,/unitsfeeds Booking, and/doctors/reservationsstores the confirmations the Client reservations tab reads back. - Let the doctor tab save through the data processor:
new scheduler.DataProcessor(URL("/doctors/worktime"))withsetTransactionMode("REST-JSON"). - Load Booking from the units endpoint: create it with
data: [], fetch/units, then callsetConfig({ data: units })andsetConfirmHandler. - Post the reservation: the handler sends
{ doctor: slot.id, date: l2g(slot.time[0]), form: { name, email, details } }.detailsis taken fromdata.description, the default form field. - Set the bookable window: the demo opens Booking on today and closes it two years out with
startandend. - Convert Booking's timestamps:
g2lwhile loadingusedSlotsand slotdates, andl2gonslot.time[0]before the reservation POST.
Good to know
- Both staff tabs are Scheduler: Doctor schedule loads
/doctorsand/doctors/worktime, and it is the only tab that creates, moves, and deletes shifts. Client reservations loads/doctorsand/doctors/reservationsinto another Scheduler with thereadonlyplugin. A click there opens the reservation details. - Booking never edits the schedule: it displays availability and returns one confirmation. Recurring rules and deletion stay on the Doctor schedule tab.
- The card id is the link:
slot.idis the id of the record loaded from/units, which is what tells the backend whose time was taken. - Rebuild a tab when it opens again: a Scheduler tab calls
destructor(), thengetSchedulerInstance(). Booking callsbookingWidget.destructor()beforenew booking.Booking. The widget you leave stays mounted.
FAQ
How do you add a public booking page to an app that already runs Scheduler?
Serve the same availability through a second endpoint and mount Booking on it. The demo loads /units into Booking and leaves both staff tabs on Scheduler. Doctor schedule edits the shifts, and Client reservations only displays what was booked, so no planning logic is duplicated.
Where do the available slots come from?
From /units. Each card uses the data format: slots, usedSlots, and slotSize. The backend builds that payload from the working time saved on the Doctor schedule tab.
Can a visitor change or cancel a booking from this widget?
No. Booking confirms one new slot. Client reservations only displays /doctors/reservations, and Doctor schedule edits shifts, so a change or a cancellation needs a screen of your own on that endpoint.
API reference
- setConfirmHandler(): Sending a confirmed slot to the reservations endpoint
- setConfig(): Loading the units into a running widget
- Working with server guide: The load, save, and UTC pattern used here
- DHTMLX Scheduler docs: The staff side of this demo
Related examples
- Event Calendar integration: the same split built on DHTMLX Event Calendar
- Backend integration: the Booking half without a second widget
- Start and end dates: set the window this demo opens with