Skip to content

Instantly share code, notes, and snippets.

@lanks
Created July 7, 2020 20:50
Show Gist options
  • Save lanks/f76bcb2dcc5803a03431db37f97bdb9a to your computer and use it in GitHub Desktop.
Save lanks/f76bcb2dcc5803a03431db37f97bdb9a to your computer and use it in GitHub Desktop.
Date range picker stimulus example
import { Controller } from "stimulus"
import moment from 'moment';
export default class extends Controller {
static targets = [ "date_range" ]
connect() {
if(this.date_rangeTarget) {
let selectedRange = false
$(this.date_rangeTarget).daterangepicker({
showCustomRangeLabel: false,
alwaysShowCalendars: true,
autoApply: false,
ranges: {
'Today': [moment(), moment()],
'Last 7 days': [moment().subtract(6, 'days'), moment()],
'Last 14 days': [moment().subtract(13, 'days'), moment()],
'Last 30 days': [moment().subtract(29, 'days'), moment()],
'This week': [moment().startOf('week'), moment().endOf('week')],
'This month': [moment().startOf('month'), moment().endOf('month')],
'Last month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
'All time': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
}
}).on('apply.daterangepicker', function(e, picker) {
if(selectedRange) {
picker.show();
selectedRange = false;
}
});
$(".ranges ul li").on("click", function() {
selectedRange = $(this).text();
});
}
}
initialize() {
}
rangeSelected(e, picker) {
}
submit(e) {
console.log("click")
this.element.submit()
}
}
@Svashta
Copy link

Svashta commented Mar 12, 2023

Hi. I am struggling with properly including/importing moment in Rails 7 and Stimulus controller.
I am getting "moment" not a function when initializing daterangepicker.
Would you be so kind and share how do you do importmap and application.js to set up moment correctly.
I can access it with window.moment, but daterangepicker is not picking it up.
Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment