Rails formatting in edit field - ruby-on-rails

Can rails formatting helpers be used on an 'edit' screen? The format helpers (number_to_currency, number_to_percent) are great for index/show, but I don't see how to apply them during edit. I have a custom heler that formats the date:
def my_date_helper(datetime)
datetime.nil? ? "" : datetime.strf('%d-%b-%Y')
end
For example, if I have a starts_at attribute, that the user interacts with using a jQuery datepicker, the value placed in edit.html.erb in <%= f.text_field :starts_at %> by rails will be formatted like:
2011/12/19 00:00:00
I would like the user to be presented with a consistent format,so I want to apply the same format helper I use in show/index so the edit text field shows a format like:
19-Jan-2011

You could do this for your edit form:
<%= f.text_field :starts_at, :value => my_date_helper(#my_model.starts_at) %>
Also, jQuery's Date Picker includes a dateFormat parameter, so you could do something like this in your javascript:
jQuery("#my_model_starts_at").datepicker({
dateFormat: 'd/M/yy'
});

I just had a 'duh' moment. To doesn't seem there's any easy, rails-ey way. But it can be done really easy with unobtrusive JavaScript, like:
$('.datepicker').each(function(i){
var date = new Date($(this).val());
$(this).val($.datepicker.formatDate('dd-M-yy', date));
});
Four lines in application.js and you're done.

jQuery('#datetimepicker3').datetimepicker({
format:'d.m.Y H:i',
inline:true,
lang:'ru'
});
datetimepicker

Related

Input multiple date from a calendar (Ruby on Rails)

I'm creating a leave management app, and I need to input multiple date into a field from calendar (jquery ui datepicker or something like that).
I've tried gem 'multi-dates-picker-rails', but it's not working.
Would you give a solution? Thank you.
You can use below jquery library file
http://dubrox.github.io/Multiple-Dates-Picker-for-jQuery-UI/
Javascript
https://raw.githubusercontent.com/dubrox/Multiple-Dates-Picker-for-jQuery-UI/master/jquery-ui.multidatespicker.js
CSS
https://raw.githubusercontent.com/dubrox/Multiple-Dates-Picker-for-jQuery-UI/master/jquery-ui.multidatespicker.css
include these file into assets
In html
<%= text_field_tag :route_dates, nil, class: "gui-input", placeholder: "Select date" %>
coffescript
date = new Date()
$('#route_dates').multiDatesPicker
addDates: [date, date]
dateFormat: 'dd-M-yy'

Using a jquery datepicker with a Rails MongoId Date field results in a "argument out of range" error

I'm trying to render a Date field for my rails model as a datepicker.
The model looks like:
class Appointment
include Mongoid::Document
field :date, type: Date
end
_form.html.haml view looks like:
= form_for #appointment, :url => {:action => :create} do |f|
= f.text_field(:date, {:class => 'datepicker'})
%button{:type => 'submit'} Book appointment
:javascript
jQuery(document).ready(function($) {
$('.datepicker').datepicker();
});
Controller action looks like:
class AppointmentsController < ApplicationController
def create
#appointment = Appointment.new(params[:appointment])
# rest left out for demo purposes
end
end
When "new" gets, called an error occurs:
ArgumentError in AppointmentsController#create
argument out of range
I know the value gets posted as MM/DD/YYYY, i.e. 03/11/2013
How can I tell Rails how to properly serialize this field?
I'm a little late to the party but...
Mongoid is pretty particular about the format of the string you feed it as a date. As I understand it, only dd-mm-yyyy will do. Fortunately the jQuery UI datepicker gives you the option to format its output. The format Mongoid wants would look like this:
$('.datepicker').datepicker({ dateFormat: 'dd-mm-yy' });
More info on the datepicker options and formats here:
http://api.jqueryui.com/datepicker/#option-dateFormat
Cheers!
Figured it out. I added another field, date_string just as an attr_accessor that won't get stored in the db but can surface to the form, and can be used to convert to the internal date field. The model is changed to be:
class Appointment
# extend these two to get accesss to drop down options
include Mongoid::Document
before_validation :parse_date_if_not_null
#person info
field :date, type: Date
attr_protected :date
attr_accessor :date_string
def parse_date_if_not_null
unless self.date_string.nil? || self.date_string == ''
self.date = Date.strptime self.date_string, '%m/%d/%Y'
end
end
end
In the view, the date_string field is used:
= form_for #appointment, :url => {:action => :create} do |f|
= f.text_field(:date_field, {:class => 'datepicker'})
%button{:type => 'submit'} Book appointment
:javascript
jQuery(document).ready(function($) {
$('.datepicker').datepicker();
});
This works correctly and I've verified the field gets set in the db correctly.
The problem is that rails/activerecord expect the date to be in ISO format 'yyyy-mm-dd'. But this not a user-friendly format
The easiest solution in my opinion is using the alt attribute on the datepicker - Basically, show a date format but submit another date format:
= f.text_field :your_date, id: "your_date", class: "hidden" // This is hidden
// This will show up
= text_field_tag "date[something_we_will_not_use]", f.object.your_date.strftime("%m/%d/%Y"),
class: "datepicker", 'data-alt-field' => '#your_date'
Datepicker initialization
$('.datepicker').each(function() {
var alt_field = $(this).attr('data-alt-field');
$this.datepicker({
dateFormat: "mm/dd/yy",
prevText: '<i class="fa fa-chevron-left"></i>',
nextText: '<i class="fa fa-chevron-right"></i>',
altField: alt_field, // This is the tag where the date will be filled
altFormat: "yy/mm/dd" // This is how the date will be posted to your controller
});
})

Active Admin date filter date format customisation

Is there simple way to change the ActiveAdmin date filter display format from the default ISO format (yyyy-mm-dd)?
Instead of overwriting the js you can provide extra options to the datepicker like this:
= f.input :my_date, as: :datepicker, datepicker_options: { dateFormat: "mm/dd/yy" }
The way i fixed is is like this:
$ ->
# reset format
$('.datepicker:not(.hasDatepicker)').each ->
if $(#).val().length > 0
p = $(#).val().split('-')
$(#).val("#{p[2]}-#{p[1]}-#{p[0]}")
# change format
$(document).on 'focus', '.datepicker:not(.hasDatepicker)', ->
$(#).datepicker dateFormat: 'dd-mm-yy'
So first reset the value from yyyy-mm-dd to yyyy-mm-dd, than set the correct format on the picker.
Hope this helps someone.
This works in ActiveAdmin pre 1 with the just_datetime_picker gem
Yes, there is. I did it with setting options for datetime picker object with js
$(document).ready(function() {
$(".datepicker").datepicker( "option", "dateFormat", 'D, d M yy' );
});
if you do this, input values will look like
Wed, 28 Nov 2012
http://docs.jquery.com/UI/Datepicker/formatDate here is manual about supported formats
For Active Admin filters..
In the Active Admin gem, file: app/assets/javascripts/active_admin/pages/application.js.coffee, you'll see:
$ ->
$(document).on 'focus', '.datepicker:not(.hasDatepicker)', ->
$(#).datepicker dateFormat: 'yy-mm-dd'
You might have to revise the on focus event, for example (file: app/assets/javascripts/active_admin.js).
$(document).ready(function(){
$(document).on('focus', '.datepicker.hasDatepicker', function() {
$(this).datepicker( "option", "dateFormat", "mm-dd-yy");
});
});
Or perhaps remove the events and re-initialize datepickers, for example:
$(document).ready(function(){
// remove existing on focus events
$._data( $(document)[0], 'events').focusin = null;
// add new datepicker with format
$('.datepicker').datepicker({dateFormat: 'mm-dd-yy'});
});
Nathan Bertram has a good solution, but I feel like it needs some exposition based on my experience and the comments of others. It helped me to look at the ActiveAdmin source for this Input as well.
ActiveAdmin does completely render the Datepicker on page load so that formatting has not been applied yet. This means that the initial value needs to be formatted as a string. Otherwise you may have the wrong format until you click on the input and select a date.
There are 2 solutions that come to mind:
strftime
I18n.l
I prefer the I18n approach because it gives you the ability to save formats for reuse
the Datepicker widget uses a different formatting syntax as compared to Ruby/Rails, make sure that you pick a format that is possible in both syntaxes. Hence the use of both: mm/dd/yy for the widget and %m/%d/%Y for the initial value
A revision of Nathan's solution:
f.input :my_date, as: :datepicker, datepicker_options: { dateFormat: "mm/dd/yy" },
input_html: { value: I18n.l(f.object.my_date, format: "%m/%d/%Y")}
In my actual implementation of this I created my own Input and applied the format in an abstracted way.
My Solution: A minor extension of the Datepicker Input
form do |f|
# ...
f.input :my_date, as: :datepicker, format: :admin_short, input_html: { value: f.object.my_date }
# ...
end
app/inputs/datepicker_input.rb
I got the idea for this looking at the source for ActiveAdmin::Inputs::DatepickerInput
class DatepickerInput < ActiveAdmin::Inputs::DatepickerInput
def input_html_options
super.tap { |hash| hash[:value] = I18n.l(hash[:value], format: format) }
end
private
def datepicker_options
super.tap do |hash|
datepicker_date_format.then do |date_format|
hash[:datepicker_options][:dateFormat] = date_format if date_format.present?
end
end
end
def datepicker_date_format
I18n.t(format, scope: "date.formats.datepicker") # => "mm/dd/yy"
end
def format
# allow for a fallback when a format is not provided
options.fetch(:format, "m-d-yy") # => :admin_short
end
end
config/locales/date_time.en.yml
en:
date:
formats:
admin_short: "%m/%d/%Y"
# datepicker format syntax will not work with I18n, here for reference
datepicker:
admin_short: "mm/dd/yy"
JS/JQuery format syntax will not work in formatting with I18n.
NOTE: I chose to put the JS/Jquery formats in this file so that they can be easily compared with the Ruby/Rails formats and to allow them to be saved in the same way with matching formats sharing the format key.
thats what makes this function work:
def datepicker_date_format
I18n.t(format, scope: "date.formats.datepicker") # => "mm/dd/yy"
end

Rails -- Can't set value for date_select in form

I'm pulling data from an API where the date data comes in as "2008-02-11 00:00:00 "
I would like that data to go into my form within the date_select as a value so I can view it correctly before I add it into my database.
The view looks like
<%= f.label :start_date %><br />
<%= f.date_select :start_date, :value => " #{#stdate[idx]} " %>
The object is actually an array of dates since I'm doing this action several times do thats why the [idx] is there; serving as an index.
<%= #stdate[idx] %> ends up outputting "2008-02-11 00:00:00 " but the fields for the date_select helper only outputs the current date "2010" "June" "5" in those dropdown date selects fields...
Do I need to set the values of the Year, Month, and Date Individually? I have Chronic and tried to parse the object before using it as a value for the date_select and that didnt work either.
Any ideas?
You wouldn't use the :value option but the :default option and pass a DateTime object to it.
There is no :value option for date_select. In your example, the value of the dropdowns will be obtained from the start_date attribute of whatever object you passed in when you started the form builder f.
On this object, you can simply set the start_date attribute before rendering, even if you're not actually saving it there.
There's also a select_date helper, which is the variant that is not linked to an object, and just allows you to pass a value. But that requires more manual labor, because it doesn't work out of the box with update_attributes.

Rails date format in form field

I'd like my dates in the mm/dd/year format in text fields. However, they currently displays as 2010-03-26.
Is there a global setting I can set to change this?
I tried the following, which seems to update the .to_s method, but form fields stay the same.
ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(:default => '%m/%d/%Y')
Thanks
You have to register the default format in an initializer.
Add this line to the config/initializers/date_time_formats.rb.
Date::DATE_FORMATS[:default] = '%m/%d/%Y'
# if you want to change the format of Time display then add the line below
Time::DATE_FORMATS[:default]= '%m/%d/%Y %H:%M:%S'
# if you want to change the DB date format.
Time::DATE_FORMATS[:db]= '%m/%d/%Y %H:%M:%S'
Now in the script\console lets test the format.
>> Date.today.to_s
=> "03/14/2010"
>> Time.now.to_s
=> "03/14/2010 13:20:55"
I don't know if there is a global setting for that anywhere, I just do it in the ERB.
<%= text_field_tag("air_date_date", air_date.blank? ? "" : air_date.strftime("%m/%d/%Y"), :class => "date-input text") %>
Alternatively, you can factor this out into a helper function to make it DRY.
I know this is an awfully old question, but you could use date_field instead of text_field. Perhaps that wasn't an option when you asked this question originally.
It displays the date in mm/dd/yyyy, which is your intent.
<%= date_field :column_name %>
The date_select form helper provides a "bare bones" date selector.

Resources