Dynamically display formatted value in f.text_field without JavaScript

61 Views Asked by At

In the database, prices are stored in cents, and it's easy to display them in the proper format, but when I try to use the text_field helper, there doesn't appear to be a way to format the money in the input's value without Javascript.

<%= form_with model: @item, local: true do |f| %>
...
  <div class="flex flex-col mb-3">
    <%= f.label :price, 'Price' %>
    <%= f.text_field :price, type:'number' %>
  </div>
...
<% end %>

Are there any ways to do this in plain HTML/Ruby, and if not, are there any simple JavaScript workarounds using the built-in Stimulus library?

2

There are 2 best solutions below

6
spickermann On BEST ANSWER

I would do that by not exposing the original, cent-based value in the form, but by using a custom dollar-based attribute.

# in app/models/item.rb
def price_in_dollars
  '%.2f' % (price / 100.0)
end

def price_in_dollars=(string)
  self.price = (string.to_f * 100).round
end

and use that attribute in the form like this:

<%= form_with model: @item, local: true do |f| %>
  ...
  <div class="flex flex-col mb-3">
    <%= f.label :price, 'Price' %>
    <%= f.text_field :price_in_dollars, type: 'number' %>
  </div>
  ...
<% end %>

Note: You will need to add price_in_dollars to the strong parameters in your controller too.

0
user513951 On

Instead of text_field, try using number_field_tag with a step attribute specified.

<%= f.number_field_tag :price, nil, step: 0.01 %>
# => <input id="price" name="price" step="0.01" type="number" />