Я работал над созданием календаря событий с использованием полного календаря. Я застрял в связи события и ресурса. Я пытаюсь получить идентификатор ресурса, когда событие было добавлено в календарь, чтобы идентификатор ресурса обновлялся в таблице событий. В моем последнем посте мне было предложено получить resourceId и вернуть его в ответе на add_resource. php, а затем использовать его при добавлении события. Я не совсем уверен, как это сделать, поскольку я очень плохо знаком с js.
В моей базе данных есть две таблицы -
resources: resourceId resourceTitle
События: id resourceId title начало конца
Вот код:
main. js
document.addEventListener("DOMContentLoaded", function() {
var containerEl = document.getElementById("external-events");
var checkbox = document.getElementById("drop-remove");
new FullCalendarInteraction.Draggable(containerEl, {
itemSelector: ".fc-event",
eventData: function(eventEl) {
return {
title: eventEl.innerText
};
}
});
var calendarEl = document.getElementById("calendar");
var calendar = new FullCalendar.Calendar(calendarEl, {
schedulerLicenseKey: "GPL-My-Project-Is-Open-Source",
plugins: ["interaction", "resourceTimeline"],
header: {
left: "promptResource today prev,next",
center: "title",
right: "resourceTimelineDay,resourceTimelineWeek"
},
customButtons: {
promptResource: {
text: "+ room",
click: function() {
var title = prompt("Room name");
console.log(title);
if (title) {
fetch("add_resources.php", {
method: "POST",
headers: {
'Accept': 'text/html'
},
body: encodeFormData({"title": title}),
})
.then(response => response.text())
.then(response => {
calendar.addResource({
id: response,
title: title
});
})
.catch(error => console.log(error));
}
}
}
},
editable: true,
aspectRatio: 1.5,
defaultView: "resourceTimelineDay",
resourceLabelText: "Rooms",
resources: "all_resources.php",
// events: "",
droppable: true,
drop: function(info) {
if (checkbox.checked) {
info.draggedEl.parentNode.removeChild(info.draggedEl);
}
},
eventLimit: true,
events: "all_events.php",
displayEventTime: false,
eventRender: function(event, element, view) {
if (event.allDay === "true") {
event.allDay = true;
} else {
event.allDay = false;
}
},
selectable: true,
selectHelper: true,
eventReceive: function(info) {
console.log(calendar.getResources());
console.log(info.event);
var eventData = {
title: info.event.title,
start: moment(info.event.start).format("YYYY-MM-DD HH:mm"),
end: moment(info.event.start).format("YYYY-MM-DD HH:mm"),
resourceId: info.event._def.resourceIds[0]
};
console.log(eventData);
//send the data via an AJAX POST request, and log any response which comes from the server
fetch("add_event.php", {
method: "POST",
headers: {
Accept: "application/json"
},
body: encodeFormData(eventData)
})
.then(response => console.log(response))
.catch(error => console.log(error));
}
});
calendar.render();
});
const encodeFormData = data => {
var form_data = new FormData();
for (var key in data) {
form_data.append(key, data[key]);
}
return form_data;
};
index. php
<link href='https://unpkg.com/@fullcalendar/core@4.4.0/main.min.css' rel='stylesheet' />
<link href='https://unpkg.com/@fullcalendar/daygrid@4.4.0/main.min.css' rel='stylesheet' />
<link href='https://unpkg.com/@fullcalendar/timegrid@4.4.0/main.min.css' rel='stylesheet' />
<script src='https://unpkg.com/@fullcalendar/core@4.4.0/main.min.js'></script>
<script src='https://unpkg.com/@fullcalendar/interaction@4.4.0/main.min.js'></script>
<script src='https://unpkg.com/@fullcalendar/daygrid@4.4.0/main.min.js'></script>
<script src='https://unpkg.com/@fullcalendar/timegrid@4.4.0/main.min.js'></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<link href='https://unpkg.com/@fullcalendar/timeline@4.4.0/main.min.css' rel='stylesheet' />
<link href='https://unpkg.com/@fullcalendar/resource-timeline@4.4.0/main.min.css' rel='stylesheet' />
<script src='https://unpkg.com/@fullcalendar/timeline@4.4.0/main.min.js'></script>
<script src='https://unpkg.com/@fullcalendar/resource-common@4.4.0/main.min.js'></script>
<script src='https://unpkg.com/@fullcalendar/resource-timeline@4.4.0/main.min.js'></script>
<link href="main.css" rel="stylesheet">
<script src='main.js'></script>
<div id='external-events'>
<p>
<strong>Draggable Events</strong>
</p>
<div class='fc-event'>My Event 1</div>
<div class='fc-event'>My Event 2</div>
<div class='fc-event'>My Event 3</div>
<div class='fc-event'>My Event 4</div>
<div class='fc-event'>My Event 5</div>
<p>
<input type='checkbox' id='drop-remove' />
<label for='drop-remove'>remove after drop</label>
</p>
</div>
<div id='calendar-container'>
<div id='calendar'></div>
</div>
add_resources. php
<?php
require 'connection.php';
$title = $_POST['title'];
$conn = DB::databaseConnection();
$conn->beginTransaction();
$sqlInsert = "INSERT INTO Resources ( resourceTitle ) VALUES ( :title )";
$stmt = $conn->prepare($sqlInsert);
$stmt->bindParam(':title', $title);
if ($stmt->execute()) {
$conn->commit();
return true;
} else {
$conn->rollback();
return false;
}
?>
add_event. php
<?php
require 'connection.php';
$resourceId = $_POST['resourceId'];
$title = $_POST['title'];
$start = $_POST['start'];
$end = $_POST['end'];
$conn = DB::databaseConnection();
$conn->beginTransaction();
$sqlInsert = "INSERT INTO Events ( resourceId, title, start, [end]) VALUES (:resourceId, :title, :start, :end)";
$stmt = $conn->prepare($sqlInsert);
$stmt->bindParam(':resourceId', $resourceId);
$stmt->bindParam(':title', $title);
$stmt->bindParam(':start', $start);
$stmt->bindParam(':end', $end);
if ($stmt->execute()) {
$conn->commit();
return true;
} else {
$conn->rollback();
return false;
}
?>