Jeremy Smith on
December 09, 2015
Custom currency input for Simple Form
Today, I was moving a standard Rails form to Simple Form and realized that one of the form inputs is actually a Bootstrap input group, with an add-on at the beginning of the input field with the proper currency symbol.
There’s no built-in way to replicate this with Simple Form, but the documentation suggests building a currency Custom Input to show the currency symbol.
In my case, I wanted to be able to pass the symbol as a parameter to the input and have it generate the appropriate markup for Bootstrap.
Here’s the custom input class I ended up adding to app/inputs:
class CurrencyInput < SimpleForm::Inputs::Base
def input(wrapper_options)
currency = options.delete(:currency) || default_currency
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
content_tag(:div, input_group(currency, merged_input_options), class: "input-group")
end
private
def input_group(currency, merged_input_options)
"#{currency_addon(currency)} #{@builder.text_field(attribute_name, merged_input_options)}".html_safe
end
def currency_addon(currency)
content_tag(:span, currency, class: "input-group-addon")
end
def default_currency
"$"
end
end
Now, all I have to do in my form is call:
<%%= f.input :registration_fee, as: :currency, currency: "€" %>
Need help building or maintaining a Rails app?
Book a one-hour project inquiry call or reach out via email.