Unable to load bulma calendar extension - javascript

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());
});
}
});

Related

Laravel Livewire: Cannot read property '$wire' of undefined

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.

How to listen input change event in Bootstrap Date Time Picker?

I'm using bootstrap date time picker in my project and I need to listen the change of a input tag in order to modify the value of a second one. I tried to liste to it with vanilla Js, jQuery and even Stimulus.js without success. I can properly listen the click event but the change doesn't work.
Here's my picker with some of attempts to listen the change event:
$('.datetimepicker').datetimepicker({
format: 'LT',
locale: 'PT-BR',
icons: {
up: "fa fa-chevron-up",
down: "fa fa-chevron-down",
time: "far fa-clock",
},
enabledHours: permittedHours(),
stepping: 15,
})
Vanilla:
const handleHourStart = () => {
let hourStart = document.getElementById('order_hour_start');
hourStart.addEventListener('input', () => {
alert('CHANGED!');
})
}
jQuery:
$(document).ready(function(){
$("#order_hour_start").change(function(){
alert($(this).val());
});
});
Stimulus.js
import { Controller } from "stimulus"
export default class extends Controller {
static targets = [ 'hour_start', 'hour_finish' ];
connect() {
console.log(this.hour_startTarget);
}
update() {
alert('Changed');
}
}
All they responds well to the click event, but doesn't for change...
I really don't know how to manage it with the picker functions, the docs are very confused to me...

Fullcalendar refetch eventsource

As the title says, I have a question regarding EventSource in the fullcalendar.
At the moment I can load 1 google calendar in the fullcalendar. And know how to add multiple google calendars.
However, I want to use checkboxes (linked to their own google calendar), I dynamically create an array with the googleCalendarIds, all this works, but I can't get the calendar to "refetch" all the event from the google calendars in the array.
At the moment, this is the code I use to populate the calendar:
document.addEventListener('DOMContentLoaded', function() {
var selected = [];
$('.badgebox:checked').each(function() {
selected.push({
'googleCalendarId' : $(this).val(),
'className' : $(this).data('color')
});
});
$('.badgebox').on('click', function() {
if($(this).prop('checked')) {
selected.push({
'googleCalendarId' : $(this).val(),
'className' : $(this).data('color')
});
$('#calendar').fullCalendar('refetchResources');
}else{
index = selected.findIndex(obj => obj.googleCalendarId === $(this).val());
selected.splice(index, 1);
$('#calendar').fullCalendar('refetchResources');
}
});
var calendarEl = document.getElementById('calendar');
calendar = new FullCalendar.Calendar(calendarEl, {
header: {
center: 'dayGridMonth,timeGridWeek'
},
views: {
dayGridMonth: {
titleFormat: { year: 'numeric', month: '2-digit', day: '2-digit' }
}
},
plugins: [ 'dayGrid', 'timeGrid', 'bootstrap', 'googleCalendar' ],
googleCalendarApiKey: 'api key',
eventSources: selected,
eventClick: function(info) {
info.jsEvent.preventDefault();
},
defaultView: 'timeGridWeek',
weekNumbers: true,
locale: 'nl',
themeSystem: 'bootstrap',
nowIndicator: true
});
calendar.render();
});
But what I am getting is an error:
TypeError: $(...).fullCalendar is not a function
I have loaded all the files needed (and can see they are loaded).
Edit current code
This is the code I use now, but still not sure how to fix the resources part (refreshing):
document.addEventListener('DOMContentLoaded', function() {
var curSource = [];
$('.badgebox:checked').each(function() {
curSource.push({
'googleCalendarId' : $(this).val(),
'className' : $(this).data('color')
});
});
var newSource = [];
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
schedulerLicenseKey: 'key',
header: {
center: 'dayGridMonth,timeGridWeek'
},
views: {
dayGridMonth: {
titleFormat: { year: 'numeric', month: '2-digit', day: '2-digit' }
}
},
plugins: [ 'dayGrid', 'timeGrid', 'bootstrap', 'googleCalendar', 'resourceTimeGrid', 'resourceDayGrid' ],
googleCalendarApiKey: 'apikey',
eventSources: curSource,
eventClick: function(info) {
info.jsEvent.preventDefault();
},
defaultView: 'timeGridWeek',
weekNumbers: true,
locale: 'nl',
themeSystem: 'bootstrap',
nowIndicator: true
});
$('.badgebox').on('change', function() {
if($(this).prop('checked')) {
newSource.push({
'googleCalendarId' : $(this).val(),
'className' : $(this).data('color')
});
}else{
index = newSource.findIndex(obj => obj.googleCalendarId === $(this).val());
newSource.splice(index, 1);
}
curSource = newSource;
calendar.getEventSources().forEach(eventSource => {
eventSource.remove()
});
calendar.addEventSource(curSource);
});
calendar.render();
});
Any idea?
Your logic for adding and removing event sources is flawed - it'll remove all the previous sources, but only ever add the currently selected one (well, except that you never clear newSource so it'll contain all sorts of duplication after a while). The other problem is that when you write calendar.addEventSource(curSource); you're adding an array of event sources (even though it only ever contains one item) but adding it as if it was a single event source object. Therefore it's not in the format fullCalendar expects, so it doesn't add anything.
Instead you can just use the same logic you use when you first declare the calendar, to loop through all the currently selected checkboxes and set all of them as the current sources. This is the simplest way to do it. Just move that logic into a function so you can re-use it. It also removes the necessity for global objects containing the list of sources. Something like this:
function getEventSources() {
var sources = [];
$(".badgebox:checked").each(function() {
sources.push({
id: $(this).val(),
'googleCalendarId' : $(this).val(),
className: $(this).data("color")
});
});
return sources;
}
Then in the calendar config, set the initial event sources by calling the function:
eventSources: getEventSources(),
And handle the "change" event on the checkboxes like this:
$(".badgebox").on("change", function() {
//remove event sources
calendar.getEventSources().forEach(eventSource => {
eventSource.remove();
});
//get currently selected sources
var sources = getEventSources();
//add each new source to the calendar
sources.forEach(eventSource => {
calendar.addEventSource(eventSource);
});
});
I made a live demo here: https://codepen.io/ADyson82/pen/Jjoovym. I couldn't use google calendars for the demo obviously so I've done it with hard-coded lists of events, but the overall logic of the process is identical.

TypeError: Cannot read property 'add' of undefined" Flatpickr & Vue.js

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>

Error in dojo 1.9 custom widget extending dijit/form/DateTextBox

Developing a custom widget extending dijit/form/DateTextBox and get the following error:Error: Unable to resolve constructor for: 'GilCnPluginDojo.util.CustomDateTextBox' Does anyone have a clue of what is going on? Can't see anything wrong. This is my code:
require(["dojo/ready",
"dojo/parser",
"dijit/form/DateTextBox",
"dojo/_base/declare",
"dijit/registry"],
function(ready, parser, DateTextBox, declare, registry) {
declare("GilCnPluginDojo.util.CustomDateTextBox", [DateTextBox], {
postCreate: function() {
this.inherited(arguments);
this.set('constraints', {
min: '01/01/1950',
max: new Date(),
datePattern: 'MM/dd/yyyy'
});
}
});
};
You need to assign your declared type to variable to create new objects. See following snippet. (I've removed unnecesary modules and it misses some css file for dropdown but it's not important here.)
require(["dijit/form/DateTextBox",
"dojo/_base/declare"],
function( DateTextBox, declare) {
var CustomDateTextBox = declare("GilCnPluginDojo.util.CustomDateTextBox", [DateTextBox], {
postCreate: function() {
this.inherited(arguments);
this.set('constraints', {
min: '01/01/1950',
max: new Date(),
datePattern: 'MM/dd/yyyy'
});
}
});
new CustomDateTextBox().placeAt('result');
});
<script src="https://ajax.googleapis.com/ajax/libs/dojo/1.9.7/dojo/dojo.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/dojo/1.9.7/dijit/themes/claro/claro.css" rel="stylesheet"/>
<div id='result' class='claro'></div>
To use your custom modules in other modules you shoud use define instead of require and return your declared class.
//CustomDateTextBox.js
define(["dijit/form/DateTextBox", "dojo/_base/declare"],
function( DateTextBox, declare) {
return declare("GilCnPluginDojo.util.CustomDateTextBox", [DateTextBox], {
//some code
});
});
//MainModule.js
require(["your/path/to/CustomDateTextBox"],
function( CustomDateTextBox) {
var cdtb = new CustomDateTextBox();
});

Categories