I have a problem with laravel livewire. I think the problem is really simple, but I can not solve it. Let me explain everything.
I have a daterangepicker (LitePicker), he works perfect, but I want when user select date range value to set this value to the property and filter data. My problem is that I can't set value to the property.
my Js Code:
#push('scripts')
<script type="text/javascript">
document.addEventListener('livewire:load', function() {
var field = document.getElementById('filter-date-range')
var dateRange;
var picker = new Litepicker({
element:field,
format: 'DD/MM/YYYY',
lang: 'de',
singleMode: false,
onSelect: function(start, end) {
#this.dateRange = start
}
});
})
</script>
#endpush
#this directive is compiled to
onSelect: function(start, end) {
window.livewire.find('').dateRange = start
}
I think the problem is here, because parameter which is passed to find function is empty or the id of the component is missing, and I don't know how to fix it.
Now here is the the error I received when date is selected:
index.js:30 Uncaught TypeError: Cannot read property '$wire' of undefined
at Livewire.value (index.js:30)
at e.onSelect (book_keeping:695)
at e.r.Litepicker.setDateRange (main.js:12)
at e.onClick (main.js:12)
at HTMLDocument.<anonymous> (main.js:12)
As you can see I use push directive so here is the code where I load the scripts
#livewireScripts
<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine#v2.7.3/dist/alpine.min.js" defer></script>
<script type="text/javascript" src="{{asset('js/app.js')}}"></script>
#stack('scripts')
Also I tried with events wire:model and wire:change without success.
I used like this
document.addEventListener('livewire:load', function() {
var field = document.getElementById('date-from')
var picker = new Litepicker({
element:field,
lang: 'de',
autoApply: false,
singleMode: true,
numberOfColumns: 1,
numberOfMonths: 1,
showWeekNumbers: true,
format: "D MMM, YYYY",
dropdowns: {
minYear: 1990,
maxYear: null,
months: true,
years: true,
},
setup: (picker) => {
picker.on('selected', (date1, date2) => {
Livewire.emit('from-selected', date1)
});
}
});
})
than in livewire
protected $listeners = ['from-selected' => 'fromSelected'];
public function fromSelected($from){
$this->from = $from;
$this->resetPage();
}
Try registering AlpineJS after Livewire Scripts.
Related
Does anybody know why is the end date null on those "allday=false" events?
Fiddle Sample: https://jsfiddle.net/L1g0z3jd/
I instantiate it differently from the start date, it shows just fine in the calendar view, but for some reason I can't understand whenever i get clientEvents, even thought i have not changed it, I got a null in the event end date!
PS: Just for the sake of "conscience" I must add ... I'm using and old version of google chrome (v 57.0.2987.133 64-bit) and an old ubuntu version (Linux Mint 18.1 Serena)
Its getting me crazy! Thanks!
HTML Code:
<button onclick="javascript:getEvents()">Get Events</button>
<div id='calendar'></div>
Javascript Code:
$(function() {
$('#calendar').fullCalendar({
header: false,
allDaySlot: false,
visibleRange: {start: moment('2000-01-02'), end: moment('2000-01-09')},
editable: true,
selectable: true,
views: {
settimana: {
type: 'agenda',
columnFormat: 'ddd',
hiddenDays: []
}
},
defaultView: 'settimana',
defaultDate: $.fullCalendar.moment().startOf('week'),
slotMinutes: 30,
events: [
$.fn.getAgendaWorktime(1, "08:00:00", 60),
$.fn.getAgendaWorktime(2, "08:30:00", 120),
],
select: function(startDate, endDate) {
$('#calendar').fullCalendar('renderEvent', {
title: 'free time',
start: startDate.format(),
end: endDate.format(),
allDay: false
});
},
eventClick: function(calEvent, jsEvent, view) {
console.log(calEvent, jsEvent, view);
if(doubleClick==calEvent._id){
if (confirm('Delete it?')) {
$('#calendar').fullCalendar('removeEvents',calEvent._id);
}
doubleClick = null;
}else{
doubleClick=calEvent._id;
}
},
});
});
function getEvents() {
var e=0,err=false,$data = []
$('#calendar').fullCalendar('clientEvents').forEach(periodo => {
if (periodo.end==null || periodo.start.format().substr(0,10)!=periodo.end.format().substr(0,10)) {
if (e==0) {
err = true;
e++;
alert('Event startint at '+periodo.start.format()+' cant spread to multiple days');
}
} else {
$data.push({'ini': periodo.start.format(), 'fim': periodo.end.format()});
}
});
alert($data);
}
jQuery.fn.getAgendaWorktime = function ($dow, $start, $elapsed) {
var r = {
allDay: false,
title: 'free time',
start: new Date('2000-01-02 '+$start),
end: new Date('2000-01-02 '+$start)
};
r.start.setDate(r.start.getDate()+$dow);
r.end.setDate(r.end.getDate()+$dow);
r.end.setHours(r.end.setHours()+($elapsed*60));
return(r);
}
I figured out how to solve the question, I will reply to it here for I have not found any workaround or further analysis of the problem in the internet ....
I didn't review my problem to determine if it was specific related to the fact that I was setting the event's end time incorrectly and the calendar wasn't giving me any errors on the issue or anything else, but if you're gowing by the same road i went i can tell you:
Check to see if the end time is been created corretly (that seams to be my real mistaken, I was using setHours instead getHours in the getAgendaWorktime function, which turned the final value to be null. I corrected it in the sample below, but let it incorrectly in the fiddle to show the use of the forceEventDuration attribute);
Set "forceEventDuration" parameter to "true" (that forces the "end" attribute to always be filled easying me up in my code for I can always awaits for an string from ".format()" method of the attibute);
for meny reasons fullcalendar.io some times does not sets the event end date and this was getting me problems whenever avaluating the event end time (Ok, I could work around it but I was intrigged for why does it was getting me those results when it sould not, and the answare was a buged code). With "forceEventDuration: true" fullcalendar gave me the end time every time therefor i could find out that the input method i was using was seting the end date incorrectly and gave me the chance to correct it as well.
Links related:
Calendar parameter documentation https://fullcalendar.io/docs/forceEventDuration
Corrected Fiddle https://jsfiddle.net/gjrfox05/
I hope this answer could be of some help for newcomers at fullcalendar.io as me.
Fiddle Javascript part corrected sample:
$(function() {
$('#calendar').fullCalendar({
header: false,
allDaySlot: false,
forceEventDuration: true,
visibleRange: {start: moment('2000-01-02'), end: moment('2000-01-09')},
editable: true,
selectable: true,
views: {
settimana: {
type: 'agenda',
columnFormat: 'ddd',
hiddenDays: []
}
},
defaultView: 'settimana',
defaultDate: $.fullCalendar.moment().startOf('week'),
slotMinutes: 30,
events: [
$.fn.getAgendaWorktime(1, "08:00:00", 60),
$.fn.getAgendaWorktime(2, "08:30:00", 120),
],
select: function(startDate, endDate) {
$('#calendar').fullCalendar('renderEvent', {
title: 'free time',
start: startDate.format(),
end: endDate.format(),
allDay: false
});
},
eventClick: function(calEvent, jsEvent, view) {
console.log(calEvent, jsEvent, view);
if(doubleClick==calEvent._id){
if (confirm('Delete it?')) {
$('#calendar').fullCalendar('removeEvents',calEvent._id);
}
doubleClick = null;
}else{
doubleClick=calEvent._id;
}
},
});
});
function getEvents() {
var e=0,err=false,$data = []
$('#calendar').fullCalendar('clientEvents').forEach(periodo => {
if (periodo.end==null || periodo.start.format().substr(0,10)!=periodo.end.format().substr(0,10)) {
if (e==0) {
err = true;
e++;
alert('Event startint at '+periodo.start.format()+' cant spread to multiple days');
}
} else {
$data.push({'ini': periodo.start.format(), 'fim': periodo.end.format()});
}
});
alert($data[0].fim);
}
jQuery.fn.getAgendaWorktime = function ($dow, $start, $elapsed) {
var r = {
allDay: false,
title: 'free time',
start: new Date('2000-01-02 '+$start),
end: new Date('2000-01-02 '+$start)
};
r.start.setDate(r.start.getDate()+$dow);
r.end.setDate(r.end.getDate()+$dow);
r.end.setHours(r.end.getHours()+($elapsed*60));
return(r);
}
By default FullCalendar end date null when event end_date = start_date.
I Just pass another fiend with same date from database (Django View).
event_sub_arr['end'] = end_date
event_sub_arr['end_same_date'] = end_date
And check in javaScript
eventClick: function(info) {
var modal = document.getElementById('DeleteEventModal')
getEventDeleteUrl(info.event.id)
getEventUpdateUrl(info.event.id)
modal.style.display = 'block'
calendar.unselect()
var start = info.event.start
var end_same_date = info.event.end_same_date
var end = info.event.end || end_same_date
$("#event_id_name").text(info.event.title)
$("#event_id_start").text(moment(start).format('h:mm:ss a, MMMM Do YYYY'))
$("#event_id_end").text(moment(end).format('h:mm:ss a, MMMM Do YYYY'))
console.log(info.event.start)
console.log(info.event.end)
console.log({{ event_data|safe }})
},
ITS WORK FOR ME
I am currently developing an appointments app in C# asp.net.
The app involves someone putting in for an appointment. Currently, I do a check when the form is submitted if the admin is not available but I would like to do it dynamically.
I am using a Javascript/jQuery DateTimePicker and ideally I would like to do the following:
The dates that no appointments are available should be grayed out
the times that are not available or when an admin are booked, should be in red
I know I need an Ajax call to carry this out but I'm at a total loss.
Here's my DateTimePicker:
<script>
$('#DateOfAppointment').datetimepicker({
format: 'd/m/Y H:i',
minDate: 0,
inline: true,
allowTimes: ['9:00', '9:30', '11:30', '12:00', '12:30', '14:00', '14:30', '15:00', '15:30', '16:00', '16:30', '17:00']
});
If anyone wants the CSS file or the script, I can make it available.
EDIT I'll include my controller method and my updated datetimepicker:
public JsonResult UnAvailableSlots()
{
var events = (from a in db.Appointments
select a).ToList();
return new JsonResult { Data = events, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
}
<script src="~/Scripts/jquery.js"></script>
<script src="~/Scripts/jquery.datetimepicker.js"></script>
<script>
$(document).ready(function () {
var events = [];
$.ajax({
type: "GET",
url: "/Appointments/UnAvailableSlots",
success: function (data) {
$.each(data, function (i, v) {
events.push({
details: v.DetailsOfAppointment,
date: moment(v.DateOfAppointment),
room: v.RoomType,
confirmed: v.Confirmed,
colour: v.ThemeColour,
church: v.Church.Name,
parishAdminName: v.Admins.AdministratorName,
parishAdminUser: v.Admins.AdminUsername,
parishAdminId: v.Admins.AdministratorId,
fee: v.Fee,
id: v.AppointmentId
});
})
GenerateCalender(events);
},
error: function (error) {
alert("failed");
console.log(error);
}
})
function GenerateCalender(events) {
$('#DateOfAppointment').datetimepicker({
format: 'd/m/Y H:i',
minDate: 0,
inline: true,
disabledDates: [events.date],
allowTimes: ['9:00', '9:30', '11:30', '12:00', '12:30', '14:00', '14:30', '15:00', '15:30', '16:00', '16:30', '17:00']
});
}
})
</script>
Too bad that this plugin does not support ajax and callbacks for allow date and times.
you'd have to set: https://xdsoft.net/jqplugins/datetimepicker/#allowDates
allowDates:['not','full','dates']
When a date is chosen you can overwrite allowTimes with:
$('#input').datetimepicker('setOptions', {allowTime:['times']});
like this:
onSelectDate:function(date,$i){
// your ajax call here with callback method updating datepicker
api.availableHoursOnDay(date,function(hoursOpen){
$('#input').datetimepicker('setOptions', {allowTime:hoursOpen});
})
alert(ct.dateFormat('d/m/Y'))
}
It might be a bit hacky. but the only other way would to be:
Download the source code and change it to your needs
Create your own plugin/datepicker.
In a new laravel project, I installed bulma-calendar using npm install bulma-calendar --save-dev. In my app.scss file, I am importing both bulma and bulma-calendar like this:
#import "~bulma";
#import "~bulma-calendar";
and in the bootstrap.js file at the top of the file I imported the minified js file:
import bulmaCalendar from 'bulma-calendar/dist/bulma-calendar.min.js'
and at the bottom of it I added this:
document.addEventListener( 'DOMContentLoaded', function () {
var datePicker = new bulmaCalendar( document.getElementById( 'datepickerDemo' ), {
startDate: new Date(), // Date selected by default
dateFormat: 'yyyy-mm-dd', // the date format `field` value
lang: 'en', // internationalization
overlay: false,
closeOnOverlayClick: true,
closeOnSelect: true,
// callback functions
onSelect: null,
onOpen: null,
onClose: null,
onRender: null
} );
var datePicker = new bulmaCalendar( document.getElementById( 'datepickerDemo2' ), {
overlay: true
} );
} );
And in my welcome.blade.php I added an input element:
<input id="datepickerDemo" class="input" type="text" value="11-02-2018">
But I don't see any calendar when I click on that input field, just as I see on the demo page. What am I missing?
Also, in the console, I am seeing this error:
TypeError: __WEBPACK_IMPORTED_MODULE_0_bulma_calendar_dist_bulma_calendar_min___default.a is not a constructor
Not sure if this would do the trick, but change the input type from "text" to "date"
<input id="datepickerDemo" class="input" type="date" value="11-02-2018">
Source: https://demo.creativebulma.net/components/calendar/v6/#html-structure
Hello i'm use laravel 6 and i had the same issue. But i found a way to resolve it and now bulma calendar work perfectly in my project.
/resources/sass/app.scss
// Import component
#import "bulma-calendar";
/resources/js/app.js :
put this on top
var bulmaCalendar=require('bulma-calendar');
after this :
document.addEventListener('DOMContentLoaded', function () {
// Initialize all input of type date
var calendars = bulmaCalendar.attach('[type="date"]', []);
// Loop on each calendar initialized
for(var i = 0; i < calendars.length; i++) {
// Add listener to date:selected event
calendars[i].on('select', date => {
console.log(date);
});
}
// To access to bulmaCalendar instance of an element
var element = document.querySelector('#my-element');
if (element) {
// bulmaCalendar instance is available as element.bulmaCalendar
element.bulmaCalendar.on('select', function(datepicker) {
console.log(datepicker.data.value());
});
}
});
in my view blade.php
`<input type="date">`
It's work for me i hope that it will help you
For an example like yours i've try this :
document.addEventListener('DOMContentLoaded', function () {
bulmaCalendar.attach('#datepickerDemoDefault', {
displayMode: 'dialog',
startDate: new Date(),
minDate: '01/01/2020',
maxDate: '12/31/2500',
lang: 'fr'
});
const element = document.querySelector('#datepickerDemoDefault');
if (element) {
// bulmaCalendar instance is available as element.bulmaCalendar
element.bulmaCalendar.on('select', function(datepicker) {
console.log(datepicker.data.value());
});
}
});
I'm trying to wrap flatpickr into a custom Vue component which should then should send dates to an eventHub, however I can't seems to get it to work. Somehow flatpickr can't find the input field (I think)
My wrapper component looks something like this:
<template>
<input type="text" id="flatpickr" placeholder="Select a range" />
</template>
<script>
const Flatpickr = require("flatpickr");
var defaultStart = new Date(new Date().setDate(new Date().getDate() - 10)).toISOString().slice(0, 10)
var defaultEnd = new Date().toISOString().slice(0, 10)
export default {
name: 'DatePicker',
props:['startDate', 'endDate'], // I don't really need this but I should pass data to all Children
mounted() {
new Flatpickr('#flatpickr', {
dateFormat: "Y-m-d",
mode: 'range',
altInput: true, // Human Readable
minDate: new Date().fp_incr(-60), // 60 days from today
maxDate: defaultEnd,
// defaultDate: [defaultStart, defaultEnd],
// minDate: '2017-01-01', // 60 days from today
// maxDate: '2017-05-05',
// defaultDate: ["2017-02-02", "2017-04-04"],
locale: { firstDayOfWeek: 1},
onClose: function(selectedDates, dateStr, instance) {
let startDate = selectedDates[0].toISOString().slice(0, 10);
let endDate = selectedDates[1].toISOString().slice(0, 10);
this.$emit('change', { startDate, endDate }); // emit to eventHub
}
})
}
}
</script>
I've also tried to use .class-name but nothing. What am I doing wrong?
Try making the following changes:
In the template...
<input type="text" ref="flatpickr" placeholder="Select a range" />
In the mounted() hook...
mounted() {
var myInput = this.$refs.flatpickr
new Flatpickr(myInput, {
Explanation:
The Vue way of identifying elements in the template is by using "ref" (instead of "id") - and it's best to keep Vue happy because it does funky things with the template which may cause unexpected behaviours if you treat it as plain HTML. (It only looks like HTML but don't be fooled... the Vue template isn't HTML, and actually ends up getting compiled into a function.)
So, replace the input's id with a "ref" instead, and in your mounted() hook, get a variable reference to the input, and use that as the first parameter of your Flatpickr() call instead of an "#id".
JSFiddle: https://jsfiddle.net/CookieJon/7stotLrz/2/
Use this vue component instead.
Installation:
npm install vue-flatpickr-component --save
It is dead simple to use.
Sample:
<template>
<div>
<flat-pickr v-model="date"></flat-pickr>
</div>
</template>
<script>
import flatPickr from 'vue-flatpickr-component';
import 'flatpickr/dist/flatpickr.css';
export default {
data () {
return {
date: null,
}
},
components: {
flatPickr
}
}
</script>
I have a C# page that has a javascript calendar on it and that caledar drives what information gets pulled for the user. The calendar is set up as follows:
if (document.getElementById("calendar-inputField")) {
var cal_inp_fld_currvalue = "";
var cal3 = Calendar.setup({
inputField: "calendar-inputField",
trigger: "calendar-inputField",
dateFormat: "%m/%d/%Y",
showsTime: false,
animation: false,
min: midDate,
max: new Date(),
fdow: 0,
singleClick: true,
step: 1,
electric: false,
onFocus: function () { cal_inp_fld_currvalue = document.getElementById('calendar-inputField').value; },
onSelect: function () { this.hide(); if (cal_inp_fld_currvalue != document.getElementById('calendar-inputField').value) { ajax_call('qbonline.aspx?fn=AJAX', document.getElementById('idSelGetBatchType').value); } }
});
the issue I'm having is with the dateformat, I found that if I use chrome and set my language settings to English (Canada) and I select a date like 05/23/2017 the calendar thinks that is an invalid date because the canadian date is viewed as dd/mm/yy.
What I want to know is if there is a way to ignore the users chrome settings and always use one format?