Implementing a datepicker – Simple ( not…!)
My RoR app is using twitter bootstrap for all my styles. Not only does this significantly reduce my need for extensive front end development, it also provides a responsive framework to enable the app to deploy to a range of devices.
The standard date field in the Twitter Bootstrap is a slightly clunky-looking set of fields for entering each component of the date (and additional fields for entering time):
I prefer a single field, and would also like to provide a date-picker option – it’s pretty standard to offer this and I prefer to see a future date in context of weeks and months. So I landed on the following, which displays the date picker when the field gets focus, but which also permits keyboard typing of the date:
So, with the goal set, it’s time to figure out how to actually implement this!
A visit to CodeAcademy and a whirlwind tour of jQuery basics, which included a simple exercise to display 2 datepickers on a page, gave me a basic understanding of the jQuery datepicker. A start, but not exactly transferrable to my Ruby on Rails Bootstrap project.
Fortunately GitHub came through with a solution (see the GitHub project for a bootstrap datepicker integrated with Rails 3 assets pipeline). There are a couple of forks – but I think the following gives me a pretty mature picker, and the implementation method seems to be the same across the forks…
There are lots of snippets and samples – but many seem to do a bunch of stuff in html and js, that I am not planning to do given I am using the bootstrap. The following works like a charm for me, although I have yet to try adding two datepickers to the same view… I’ll start with the small wins!
- Add the datepicker gem to my Gemfile:
Run bundle install
- Update the assets stylesheets application.css.scss, by adding
*= require bootstrap-datepicker
Inserted above the line for *= require_tree .
//= require bootstrap-datepicker
Inserted above the line for //= require_tree .
- Update target view’s coffee.js with:
$(document).on "focus", "[data-behaviour~='datepicker']", (e) -> - $(this).datepicker - format: "dd-mm-yyyy" - weekStart: 1 - autoclose: true
- Update the target view’s .erb (e.g. _form.html.erb)
For me, that meant removing:
<%= f.datetime_select :review_date %>
<%= f.text_field :review_date, 'data-behaviour' => 'datepicker' %>
And that’s my “how to” for future reference. Still on the task list:
- Check if this implementation is compatible with Rails 4.
- Determine if this implementation will support multiple dates on a single view.
- Verify on a range of browsers/devices.
- Display the required date format (infield) for keyboard users (e.g. dd/mm/yy).
On y va!