OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

fullcalendar with resourcetimeline laravel php [closed]

  • Thread starter Thread starter mohammed naseralla
  • Start date Start date
M

mohammed naseralla

Guest
How can I use Draggable events, read start and end dates from the event and fix them, but allow the user to choose the resource?

This is my fullCalendar code with Draggable. The resources and events are read by the php code, but some things do not read from php read by design. How to do it?

Code:
    <script id="rendered-js">
        document.addEventListener('DOMContentLoaded', function () {

            var date = new Date()
            var d = date.getDate(),
                m = date.getMonth(),
                y = date.getFullYear()

            var Calendar = FullCalendar.Calendar;
            //var Draggable = FullCalendar.Draggable;

            var containerEl = document.getElementById('external-events');
            var checkbox = document.getElementById('drop-remove');

            var Draggable = FullCalendarInteraction.Draggable;

            new Draggable(containerEl, {
                itemSelector: '.external-event',
                eventData: function (eventEl) {
                    return {
                        id: eventEl.getAttribute('data-id'),
                        title: eventEl.getAttribute('data-title'),
                        start: eventEl.getAttribute('data-start'),
                        end: eventEl.getAttribute('data-end'),
                        resourceId: eventEl.getAttribute('data-resource-id'),
                        description: eventEl.getAttribute('data-description'),
                        backgroundColor: window.getComputedStyle(eventEl, null).getPropertyValue('background-color'),
                        borderColor: window.getComputedStyle(eventEl, null).getPropertyValue('background-color'),
                        textColor: window.getComputedStyle(eventEl, null).getPropertyValue('color')
                    };
                }
            });


            let calendarEl = document.getElementById('calendar');
            let calendar;

            let start = '2024-05-01';
            let end = '2024-06-31';

            let resourcesurl = '/resources';//alert(resourcesurl);
            let zone = '{{$zone}}';
            let available = '{{$available}}';
            let resourcesIndex = 0;

            if (zone === '1') {
                resourcesIndex += 1;
                if (resourcesIndex === 1) {
                    resourcesurl += '?zone=on';
                } else {
                    resourcesurl += '&zone=on';
                }
            }
            if (available === '1') {
                resourcesIndex += 1;
                if (resourcesIndex === 1) {
                    resourcesurl += '?available=on';
                } else {
                    resourcesurl += '&available=on';
                }
            }

            @foreach ($Branches as $key => $branch)
                @isset($data['BranchChoose'.$key])
                resourcesIndex += 1;
            if (resourcesIndex === 1) {
                resourcesurl += '?BranchID' + {{$key}} + '=' + {{$data['BranchID'.$key]}} + '';
            } else {
                resourcesurl += '&BranchID' + {{$key}} + '=' + {{$data['BranchID'.$key]}} + '';
            }
            @endisset
            @endforeach

            calendar = new FullCalendar.Calendar(calendarEl, {
                plugins: ['interaction', 'resourceTimeline'],
                timeZone: 'UTC',
                defaultView: 'resourceTimelineDay',
                aspectRatio: 1.5,
                header: {
                    left: 'prev,next',
                    center: 'title',
                    right: 'resourceTimelineDay'//,resourceTimelineWeek,resourceTimelineMonth
                },

                views: {
                    resourceTimelineDay: {
                        duration: {days: 10},
                        // type: 'timeline',
                        slotDuration: '{{$plus}}'
                    }
                },

                now: '{{$start_str_now}}',
                editable: true,
                droppable: true,
                resourceLabelText: '@lang("Car Plate Number")',
                resources: resourcesurl,//resourcesurl,//'/resources?zone=on&available=on',//resourcesurl,//'/resources',
                events: '/events?days=10&date={{$start_str_now}}',//?start=${start}&end=${end}

                eventRender: function (info) {

                    var eventObj = info.event;
                    var start = eventObj.start;
                    var end = eventObj.end;
                    var title = eventObj.title;

                    console.log('Event: ' + title + '\nStart: ' + start + '\nEnd: ' + end);

                    // // Fix the start and end dates here
                    // info.event.setStart('2024-06-23T00:00:00'); // Example fixed start date
                    // info.event.setEnd('2024-06-30T00:00:00');   // Example fixed end date

                    // Clear any existing icons
                    info.el.querySelectorAll('.custom-icon').forEach(function (icon) {
                        icon.remove();
                    });

                    let titleEl = '';

                    // Add custom icons before the title
                    if (info.event.extendedProps.icons) {
                         titleEl = info.el.querySelector('.fc-title');
                        info.event.extendedProps.icons.forEach(function (iconData) {
                            var icon = document.createElement('span');
                            icon.classList.add('custom-icon');
                            icon.innerHTML = iconData.html;
                            icon.setAttribute('title', iconData.tooltip); // Set tooltip for icon
                            // Insert icon before the title element
                            titleEl.parentNode.insertBefore(icon, titleEl);
                        });
                    }

                    // Set tooltip for the title
                    if (info.event.extendedProps.tooltip) {
                        info.el.querySelector('.fc-title').setAttribute('title', info.event.extendedProps.tooltip);
                    }


                    // info.event.start = 'Sun Jun 23 2024 03:00:00 GMT+0300 (GMT+03:00)';
                    // info.event.end = 'Sun Jun 30 2024 03:00:00 GMT+0300 (GMT+03:00)';
                    {{--console.log('Event id:',info.event.id);--}}
                    {{--$.ajax({--}}
                    {{--    url: '/calendar/ID',--}}
                    {{--    method: 'POST',--}}
                    {{--    data: {--}}
                    {{--        id: info.event.id,--}}
                    {{--        resourceId: info.event.id,--}}
                    {{--        // start: startDate,--}}
                    {{--        // end: endDate,--}}
                    {{--        _token: '{{ csrf_token() }}'--}}
                    {{--    },--}}
                    {{--    success: function(response) {--}}
                    {{--        // Assuming the response contains new start and end dates--}}
                    {{--        var newStart = response.start;--}}
                    {{--        var newEnd = response.end;--}}

                    {{--        info.event.setStart(newStart);--}}
                    {{--        info.event.setEnd(newEnd);--}}

                    {{--        console.log('Event newstart:',newStart);--}}
                    {{--        console.log('Event newend:',newEnd);--}}
                    {{--    },--}}
                    {{--    error: function (xhr) {--}}
                    {{--        info.revert();--}}
                    {{--    }--}}
                    {{--});--}}



                    // Calculate and display the duration
                    if (info.event.start && info.event.end) {
                        console.log('Event start:',info.event.start);
                        console.log('Event end:',info.event.end);

                        var duration = moment(info.event.end).diff(moment(info.event.start), 'hours');
                        var durationEl = document.createElement('span');
                        durationEl.classList.add('event-duration');
                        durationEl.innerText = `(${duration} hrs)`;

                         titleEl = info.el.querySelector('.fc-title');
                        if (titleEl) {
                            titleEl.appendChild(durationEl);
                        } else {
                            var timeEl = document.createElement('div');
                            timeEl.classList.add('fc-title');
                            timeEl.appendChild(durationEl);
                            info.el.appendChild(timeEl);
                        }
                    }

                    console.log('Event ID:', info.event.id);

                    console.log('Event ID:', 222222);
                },

                dateClick: function (info) {
                    var selectedDate = info.dateStr;
                    var elements = document.querySelectorAll('.fc-daygrid-day[data-date="' + selectedDate + '"]');
                    elements.forEach(function (element) {
                        element.style.backgroundColor = 'lightgreen';
                    });
                    console.log('Event ID:', 111111);
                },

                eventDidMount: function (info) {
                    // Change background on hover

                    // console.log('Event ID:', element.style.backgroundColor);

                    let element = info.el;
                    let originalBackground = element.style.backgroundColor;

                    // console.log('Event ID:', element.style.backgroundColor);

                    element.addEventListener('mouseover', function () {
                        // console.log('Event ID:', element.style.backgroundColor);
                        element.style.backgroundColor = 'lightgreen';
                    });

                    element.addEventListener('mouseout', function () {
                        // console.log('Event ID:', element.style.backgroundColor);
                        element.style.backgroundColor = originalBackground;
                    });
                },
                drop: function (info) {
                    if ($('#drop-remove').is(':checked')) {
                        info.draggedEl.parentNode.removeChild(info.draggedEl);
                    }
                },
                eventReceive: function(info) {
                    var event = info.event;

                    // Get start and end dates
                    // var startDate = event.start.toISOString();
                    // var endDate = event.end ? event.end.toISOString() : startDate;

                    console.log('Event ID:', event.id);
                    //console.log('Resource ID:', event.getResources()[0].id);
                    // console.log('Start Date:', startDate);
                    // console.log('End Date:', endDate);

                    $.ajax({
                        url: '/calendar/update',
                        method: 'POST',
                        data: {
                            id: event.id,
                            resourceId: event.getResources()[0].id,
                            // start: startDate,
                            // end: endDate,
                            _token: '{{ csrf_token() }}'
                        },
                        success: function (response) {
                            alert(response.success);
                            calendar.refetchEvents();
                        },
                        error: function (xhr) {
                            info.revert();
                        }
                    });
                },
                eventDrop: function (event, delta, revertFunc) {
                    //console.log('Event ID:', event.event.id);
                    //console.log('Event ID:', event.event._def.resourceIds[0]);
                    $.ajax({
                        url: '/calendar/update',
                        method: 'POST',
                        data: {
                            id: event.event.id,
                            resourceId: event.event._def.resourceIds[0],
                            _token: '{{ csrf_token() }}'
                        },
                        success: function (response) {
                            alert(response.success);
                        },
                        error: function (xhr) {
                            revertFunc();
                        }
                    });
                },

            });
            calendar.render();

            $('.fc-event').mouseenter(function () {
                $(this).addClass('fc-event-hover');
            });
            $('.fc-event').mouseleave(function () {
                $(this).removeClass('fc-event-hover');
            });

            // // Initialize the external events
            // $('#external-events .external-event').each(function () {
            //     // Store data so the calendar knows to render an event upon drop
            //     $(this).data('event', {
            //         title: $.trim($(this).text()), // Use the element's text as the event title
            //         stick: true // Maintain the event on the calendar after it is dropped
            //     });
            //
            //     // Make the event draggable using jQuery UI
            //     $(this).draggable({
            //         zIndex: 999,
            //         revert: true, // Will cause the event to go back to its original position after the drag
            //         revertDuration: 0 // 0 means no animation
            //     });
            //
            // });

            // Initialize the external events
            $('#external-events .external-event').each(function () {
                // Make the event draggable using jQuery UI
                $(this).draggable({
                    zIndex: 999,
                    revert: true, // Will cause the event to go back to its original position after the drag
                    revertDuration: 0, // 0 means no animation
                    // Use the helper function to create a clone that represents the event
                    helper: function () {
                        var title = $(this).text().trim();
                        return $('<div class="fc-event">').text(title);
                    },
                    // Pass the event data to FullCalendar on drag start
                    start: function (event, ui) {
                        var eventData = {
                            id: $(this).attr('data-id'),
                            title: $(this).text().trim(),
                            start: $(this).attr('data-start'),
                            end: $(this).attr('data-end'),
                            resourceId: $(this).attr('data-resource-id'),
                            description: $(this).attr('data-description'),
                            backgroundColor: window.getComputedStyle(this, null).getPropertyValue('background-color'),
                            borderColor: window.getComputedStyle(this, null).getPropertyValue('background-color'),
                            textColor: window.getComputedStyle(this, null).getPropertyValue('color')
                        };
                        // Store the event data on the dragged element
                        $(this).data('eventData', eventData);
                    }
                });
            });
        });
        //# sourceURL=pen.js
    </script>

My events have data-start and data-end and I want read those in fullcalendar with fixed values but choose resource.

Code:
        <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
                    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
                    <div class="card">
                        <div class="card-header">
                            <h4 class="card-title">Draggable Events</h4>
                        </div>
                        <div class="card-body">
                            <div id="external-events">
                                <!-- PHP loop to generate draggable events -->
                                @foreach ($events as $event)
                                    <div class="external-event"
                                         id="event_{{ $event->id }}"
                                         data-id="{{ $event->id }}"
                                         data-title="{{ $event->title }}"
                                         data-start="{{ $event->start }}"
                                         data-end="{{ $event->end }}"
                                         data-resource-id="{{ $event->resourceId }}"
                                         data-description="{{ $event->description }}"
                                         style="background-color: {{ $event->color }}; color: white;">
                                        {{ $event->title }}
                                    </div>
                                @endforeach
                                <div class="checkbox">
                                    <label for="drop-remove">
                                        <input type="checkbox" checked="checked" readonly id="drop-remove">
                                        remove after drop
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>

<p>How can I use Draggable events, read start and end dates from the event and fix them, but allow the user to choose the resource?</p>
<p>This is my fullCalendar code with Draggable. The resources and events are read by the php code, but some things do not read from php read by design. How to do it?</p>
<pre><code> <script id="rendered-js">
document.addEventListener('DOMContentLoaded', function () {

var date = new Date()
var d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear()

var Calendar = FullCalendar.Calendar;
//var Draggable = FullCalendar.Draggable;

var containerEl = document.getElementById('external-events');
var checkbox = document.getElementById('drop-remove');

var Draggable = FullCalendarInteraction.Draggable;

new Draggable(containerEl, {
itemSelector: '.external-event',
eventData: function (eventEl) {
return {
id: eventEl.getAttribute('data-id'),
title: eventEl.getAttribute('data-title'),
start: eventEl.getAttribute('data-start'),
end: eventEl.getAttribute('data-end'),
resourceId: eventEl.getAttribute('data-resource-id'),
description: eventEl.getAttribute('data-description'),
backgroundColor: window.getComputedStyle(eventEl, null).getPropertyValue('background-color'),
borderColor: window.getComputedStyle(eventEl, null).getPropertyValue('background-color'),
textColor: window.getComputedStyle(eventEl, null).getPropertyValue('color')
};
}
});


let calendarEl = document.getElementById('calendar');
let calendar;

let start = '2024-05-01';
let end = '2024-06-31';

let resourcesurl = '/resources';//alert(resourcesurl);
let zone = '{{$zone}}';
let available = '{{$available}}';
let resourcesIndex = 0;

if (zone === '1') {
resourcesIndex += 1;
if (resourcesIndex === 1) {
resourcesurl += '?zone=on';
} else {
resourcesurl += '&zone=on';
}
}
if (available === '1') {
resourcesIndex += 1;
if (resourcesIndex === 1) {
resourcesurl += '?available=on';
} else {
resourcesurl += '&available=on';
}
}

@foreach ($Branches as $key => $branch)
@isset($data['BranchChoose'.$key])
resourcesIndex += 1;
if (resourcesIndex === 1) {
resourcesurl += '?BranchID' + {{$key}} + '=' + {{$data['BranchID'.$key]}} + '';
} else {
resourcesurl += '&BranchID' + {{$key}} + '=' + {{$data['BranchID'.$key]}} + '';
}
@endisset
@endforeach

calendar = new FullCalendar.Calendar(calendarEl, {
plugins: ['interaction', 'resourceTimeline'],
timeZone: 'UTC',
defaultView: 'resourceTimelineDay',
aspectRatio: 1.5,
header: {
left: 'prev,next',
center: 'title',
right: 'resourceTimelineDay'//,resourceTimelineWeek,resourceTimelineMonth
},

views: {
resourceTimelineDay: {
duration: {days: 10},
// type: 'timeline',
slotDuration: '{{$plus}}'
}
},

now: '{{$start_str_now}}',
editable: true,
droppable: true,
resourceLabelText: '@lang("Car Plate Number")',
resources: resourcesurl,//resourcesurl,//'/resources?zone=on&available=on',//resourcesurl,//'/resources',
events: '/events?days=10&date={{$start_str_now}}',//?start=${start}&end=${end}

eventRender: function (info) {

var eventObj = info.event;
var start = eventObj.start;
var end = eventObj.end;
var title = eventObj.title;

console.log('Event: ' + title + '\nStart: ' + start + '\nEnd: ' + end);

// // Fix the start and end dates here
// info.event.setStart('2024-06-23T00:00:00'); // Example fixed start date
// info.event.setEnd('2024-06-30T00:00:00'); // Example fixed end date

// Clear any existing icons
info.el.querySelectorAll('.custom-icon').forEach(function (icon) {
icon.remove();
});

let titleEl = '';

// Add custom icons before the title
if (info.event.extendedProps.icons) {
titleEl = info.el.querySelector('.fc-title');
info.event.extendedProps.icons.forEach(function (iconData) {
var icon = document.createElement('span');
icon.classList.add('custom-icon');
icon.innerHTML = iconData.html;
icon.setAttribute('title', iconData.tooltip); // Set tooltip for icon
// Insert icon before the title element
titleEl.parentNode.insertBefore(icon, titleEl);
});
}

// Set tooltip for the title
if (info.event.extendedProps.tooltip) {
info.el.querySelector('.fc-title').setAttribute('title', info.event.extendedProps.tooltip);
}


// info.event.start = 'Sun Jun 23 2024 03:00:00 GMT+0300 (GMT+03:00)';
// info.event.end = 'Sun Jun 30 2024 03:00:00 GMT+0300 (GMT+03:00)';
{{--console.log('Event id:',info.event.id);--}}
{{--$.ajax({--}}
{{-- url: '/calendar/ID',--}}
{{-- method: 'POST',--}}
{{-- data: {--}}
{{-- id: info.event.id,--}}
{{-- resourceId: info.event.id,--}}
{{-- // start: startDate,--}}
{{-- // end: endDate,--}}
{{-- _token: '{{ csrf_token() }}'--}}
{{-- },--}}
{{-- success: function(response) {--}}
{{-- // Assuming the response contains new start and end dates--}}
{{-- var newStart = response.start;--}}
{{-- var newEnd = response.end;--}}

{{-- info.event.setStart(newStart);--}}
{{-- info.event.setEnd(newEnd);--}}

{{-- console.log('Event newstart:',newStart);--}}
{{-- console.log('Event newend:',newEnd);--}}
{{-- },--}}
{{-- error: function (xhr) {--}}
{{-- info.revert();--}}
{{-- }--}}
{{--});--}}



// Calculate and display the duration
if (info.event.start && info.event.end) {
console.log('Event start:',info.event.start);
console.log('Event end:',info.event.end);

var duration = moment(info.event.end).diff(moment(info.event.start), 'hours');
var durationEl = document.createElement('span');
durationEl.classList.add('event-duration');
durationEl.innerText = `(${duration} hrs)`;

titleEl = info.el.querySelector('.fc-title');
if (titleEl) {
titleEl.appendChild(durationEl);
} else {
var timeEl = document.createElement('div');
timeEl.classList.add('fc-title');
timeEl.appendChild(durationEl);
info.el.appendChild(timeEl);
}
}

console.log('Event ID:', info.event.id);

console.log('Event ID:', 222222);
},

dateClick: function (info) {
var selectedDate = info.dateStr;
var elements = document.querySelectorAll('.fc-daygrid-day[data-date="' + selectedDate + '"]');
elements.forEach(function (element) {
element.style.backgroundColor = 'lightgreen';
});
console.log('Event ID:', 111111);
},

eventDidMount: function (info) {
// Change background on hover

// console.log('Event ID:', element.style.backgroundColor);

let element = info.el;
let originalBackground = element.style.backgroundColor;

// console.log('Event ID:', element.style.backgroundColor);

element.addEventListener('mouseover', function () {
// console.log('Event ID:', element.style.backgroundColor);
element.style.backgroundColor = 'lightgreen';
});

element.addEventListener('mouseout', function () {
// console.log('Event ID:', element.style.backgroundColor);
element.style.backgroundColor = originalBackground;
});
},
drop: function (info) {
if ($('#drop-remove').is(':checked')) {
info.draggedEl.parentNode.removeChild(info.draggedEl);
}
},
eventReceive: function(info) {
var event = info.event;

// Get start and end dates
// var startDate = event.start.toISOString();
// var endDate = event.end ? event.end.toISOString() : startDate;

console.log('Event ID:', event.id);
//console.log('Resource ID:', event.getResources()[0].id);
// console.log('Start Date:', startDate);
// console.log('End Date:', endDate);

$.ajax({
url: '/calendar/update',
method: 'POST',
data: {
id: event.id,
resourceId: event.getResources()[0].id,
// start: startDate,
// end: endDate,
_token: '{{ csrf_token() }}'
},
success: function (response) {
alert(response.success);
calendar.refetchEvents();
},
error: function (xhr) {
info.revert();
}
});
},
eventDrop: function (event, delta, revertFunc) {
//console.log('Event ID:', event.event.id);
//console.log('Event ID:', event.event._def.resourceIds[0]);
$.ajax({
url: '/calendar/update',
method: 'POST',
data: {
id: event.event.id,
resourceId: event.event._def.resourceIds[0],
_token: '{{ csrf_token() }}'
},
success: function (response) {
alert(response.success);
},
error: function (xhr) {
revertFunc();
}
});
},

});
calendar.render();

$('.fc-event').mouseenter(function () {
$(this).addClass('fc-event-hover');
});
$('.fc-event').mouseleave(function () {
$(this).removeClass('fc-event-hover');
});

// // Initialize the external events
// $('#external-events .external-event').each(function () {
// // Store data so the calendar knows to render an event upon drop
// $(this).data('event', {
// title: $.trim($(this).text()), // Use the element's text as the event title
// stick: true // Maintain the event on the calendar after it is dropped
// });
//
// // Make the event draggable using jQuery UI
// $(this).draggable({
// zIndex: 999,
// revert: true, // Will cause the event to go back to its original position after the drag
// revertDuration: 0 // 0 means no animation
// });
//
// });

// Initialize the external events
$('#external-events .external-event').each(function () {
// Make the event draggable using jQuery UI
$(this).draggable({
zIndex: 999,
revert: true, // Will cause the event to go back to its original position after the drag
revertDuration: 0, // 0 means no animation
// Use the helper function to create a clone that represents the event
helper: function () {
var title = $(this).text().trim();
return $('<div class="fc-event">').text(title);
},
// Pass the event data to FullCalendar on drag start
start: function (event, ui) {
var eventData = {
id: $(this).attr('data-id'),
title: $(this).text().trim(),
start: $(this).attr('data-start'),
end: $(this).attr('data-end'),
resourceId: $(this).attr('data-resource-id'),
description: $(this).attr('data-description'),
backgroundColor: window.getComputedStyle(this, null).getPropertyValue('background-color'),
borderColor: window.getComputedStyle(this, null).getPropertyValue('background-color'),
textColor: window.getComputedStyle(this, null).getPropertyValue('color')
};
// Store the event data on the dragged element
$(this).data('eventData', eventData);
}
});
});
});
//# sourceURL=pen.js
</script>
</code></pre>
<p>My events have data-start and data-end and I want read those in fullcalendar with fixed values but choose resource.</p>
<pre><code> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<div class="card">
<div class="card-header">
<h4 class="card-title">Draggable Events</h4>
</div>
<div class="card-body">
<div id="external-events">
<!-- PHP loop to generate draggable events -->
@foreach ($events as $event)
<div class="external-event"
id="event_{{ $event->id }}"
data-id="{{ $event->id }}"
data-title="{{ $event->title }}"
data-start="{{ $event->start }}"
data-end="{{ $event->end }}"
data-resource-id="{{ $event->resourceId }}"
data-description="{{ $event->description }}"
style="background-color: {{ $event->color }}; color: white;">
{{ $event->title }}
</div>
@endforeach
<div class="checkbox">
<label for="drop-remove">
<input type="checkbox" checked="checked" readonly id="drop-remove">
remove after drop
</label>
</div>
</div>
</div>
</div>
</code></pre>
 

Latest posts

A
Replies
0
Views
1
Alfredo Augusto Petri
A
Top