Skip to content

Instantly share code, notes, and snippets.

@progapandist
Last active March 10, 2018 16:29
Show Gist options
  • Save progapandist/160e457781ae1c286af038db617bcef4 to your computer and use it in GitHub Desktop.
Save progapandist/160e457781ae1c286af038db617bcef4 to your computer and use it in GitHub Desktop.

Plugging a Datepicker

Let's put an end to datepicker suffering! Follow this steps to have your shiny new datepicker working in no time! (and remind yourselves of JS plugins in Rails)

Note: We recommend using Bootstrap Datepicker (try your own luck with anything different and remember, jQuery-UI's datepicker sucks, don't use it). These are the only three links you need:

  1. Docs
  2. Demo. Where you can play with different settings.
  3. Rails Gem. Don't try setting up without it!

Now, some ancient history you had during lectures on frontend and frontend setup in Rails. What do we need to setup any JS thing in our app?

  1. JS code (obviously). Where is it? Well, how about the gem?
# Gemfile
gem 'bootstrap-datepicker-rails'
  1. Rails has a fancy little thing called Assets Pipeline, everything should be "registered" there. That means, requiring JS and CSS parts of our plugin

JS:

# application.js

//= require bootstrap-datepicker  <--- add this line right after bootstrap and jquery, right before //=require tree .

CSS:

# application.scss

 @import "bootstrap-datepicker";   <--- don't forget the semicolon
  1. NOT DONE YET! What about actually making our datepicker work in forms? Create a file named init_datepicker.js in your app/assets/javascripts. Put this inside:
$('.datepicker').datepicker({
   <-- you can pass options here! Get them on the demo page by playing with settings
});
  1. Step 3 means that datepicker will be activated on any text input field that has a datepicker class on it. With simple form:
# your form view

<%= simple_form_for @thing_that_has_a_date_attribute do |f| %>
 <%= f.input :date, as: :string, input_html: { class: 'datepicker' } %>
 <%= f.button :submit %>
<% end %>

DONE!

P.S. This sequence of steps is easily adoptable to any JS plugin, remember they should (ideally) all have:

  • a gem (google for "NAME_OF_YOUR_PLUGIN Assets Pipeline")
  • a way to be present in application.js
  • a way to be present in application.scss
  • a way to initialize themselves (probably creating a new file in assets/javascripts is in order)
  • a way to hook onto elements in your DOM (classes, ids on that elements that an initializer will recognize)
@adesurirey
Copy link

adesurirey commented Nov 30, 2017

How do you get it back to format date in your controler ?

I had to give the following option

$('.datepicker').datepicker({
    format: "dd/mm/yyyy"
});

in order to Date.parse(params[:date])

Is there a lighter way you'd recommend ?

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