Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I format the value shown in a Rails edit field?

I would like to make editing form fields as user-friendly as possible. For example, for numeric values, I would like the field to be displayed with commas (like number_with_precision).

This is easy enough on the display side, but what about editing? Is there a good way to do this?

I am using the Rails FormBuilder. Upon investigation, I found that it uses InstanceTag, which gets the values for fields by using <attribute>_value_before_type_cast which means overriding <attribute> won't get called.

like image 424
Luke Francl Avatar asked Feb 26 '09 18:02

Luke Francl


4 Answers

The best I have come up with so far is something like this:

<%= f.text_field :my_attribute, :value => number_with_precision(f.object.my_attribute) %>

Or my_attribute could return the formatted value, like this:

def my_attribute
  ApplicationController.helpers.number_with_precision(read_attribute(:my_attribute))
end

But you still have to use :value

<%= f.text_field :my_attribute, :value => f.object.my_attribute %>

This seems like a lot of work.

like image 198
Luke Francl Avatar answered Oct 29 '22 21:10

Luke Francl


I prefer your first answer, with the formatting being done in the view. However, if you want to perform the formatting in the model, you can use wrapper methods for the getter and setter, and avoid having to use the :value option entirely.

You'd end up with something like this.

def my_attribute_string
  foo_formatter(myattribute)
end

def my_attribute_string=(s)
  # Parse "s" or do whatever you need to with it, then set your real attribute.
end

<%= f.text_field :my_attribute_string %>

Railscasts covered this with a Time object in a text_field in episode #32. The really clever part of this is how they handle validation errors. It's worth watching the episode for that alone.

like image 22
jdl Avatar answered Oct 29 '22 21:10

jdl


This is an old question, but in case anyone comes across this you could use the number_to_X helpers. They have all of the attributes you could ever want for displaying your edit value:

<%= f.text_field :my_number, :value => number_to_human(f.object.my_number, :separator => '', :unit => '', :delimiter => '', :precision => 0) %>

There are more attributes available too: http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html

like image 5
Joshua Harris Avatar answered Oct 29 '22 21:10

Joshua Harris


If you want a format to be created or maintained during editing, you will need to add Javascript to implement "masks." Here is a demo.

It was the first hit in these results.

like image 3
Ian Terrell Avatar answered Oct 29 '22 22:10

Ian Terrell