Tuesday, August 28, 2007

Rails: calendar_field helper

Yet another long overdue update. I'm currently working at a fun company where I've been doing some Ruby on Rails applications. We've settled on the javascript calendar from Dynarch for date fields in our projects. Of course, there's a bit of tedium involved with setting up the calendar for each field you want to use it in. Hooray for Rails.. my very first helper method eases some of this tedium. Just copy the two following functions into your application_helper.rb


def calendar_field(object_name, method, options = {})
object = instance_variable_get("@#{object_name}")
field_value = object.send(method) ? object.send(method).strftime("%m/%d/%Y") : ''
output = text_field object_name , method , :value => field_value
output += calendar_helper(object_name + "_" + method)
output
end

def calendar_helper(field_id)
'<script type="text/javascript">
Calendar.setup({
inputField : "'+ field_id + '", // id of the input field
ifFormat : "%m/%d/%Y", // format of the input field
showsTime : false,
timeFormat : "24",
singleClick : true
});
</script>'
end


and call it in your views like so


<%= calendar_field 'object', 'method' %>


Sure, you can combine both functions into one and add a date format as a param but so far this serves my quick and dirty needs.