Last active
July 14, 2022 15:23
-
-
Save fabien-michel/bdf427d4f9e6259d3dc2 to your computer and use it in GitHub Desktop.
Activeadmin datepicker returning ISO formatted date but displaying in a custom date format
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Usage : f.input :my_date_field, as: :datepicker, datepicker_options: {dateFormat: 'mm-dd-yy'} | |
# Default dateFormat french : dd/mm/yy | |
class DatepickerInput < ActiveAdmin::Inputs::DatepickerInput | |
def to_html | |
input_wrapping do | |
# New field options inherit from given input_html_options | |
new_input_html_options = input_html_options | |
# Avoid two inputs with the same id. Only the hidden input get the official id | |
new_input_html_options[:id] = nil | |
# Force text input | |
new_input_html_options[:type] = "text" | |
# Convert initial value to the specified jquery datepicker format | |
value = @object.send(method) | |
if value.is_a? Date | |
new_input_html_options[:value] = value.strftime(convert_date_format_to_ruby(date_format)) | |
end | |
# Empty input_html_options as the hidden field doesn't need it | |
input_html_options = nil | |
# Output label | |
label_html << | |
# Output field as hidden field | |
builder.hidden_field(method) << | |
# Output display date field | |
template.content_tag(:input, "", new_input_html_options) | |
end | |
end | |
private | |
# Called in ActiveAdmin::Inputs::DatepickerInput#input_html_options | |
def datepicker_options | |
super.tap do |options| | |
options[:datepicker_options]['dateFormat'] = date_format | |
options[:datepicker_options]['altField'] = "##{dom_id}" | |
options[:datepicker_options]['altFormat'] = 'yy-mm-dd' | |
end | |
end | |
# Return the specified date_format or a default one | |
def date_format | |
if options[:datepicker_options].present? && options[:datepicker_options][:dateFormat].present? | |
options[:datepicker_options][:dateFormat] | |
else | |
"dd/mm/yy" | |
end | |
end | |
# Concert date format from jquery datepicker's one to ruby's one | |
def convert_date_format_to_ruby(jquery_datepicker_format) | |
jquery_datepicker_format.gsub(/dd|mm|yy|d|m|y/, | |
'dd'=>'%d', | |
'mm'=>'%m', | |
'yy'=>'%Y', | |
'd'=>'%-d', | |
'm'=>'%-m', | |
'y'=>'%y') | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment