simple_form custom input with custom wrapper

caarlos0 picture caarlos0 · Mar 14, 2013 · Viewed 9.4k times · Source

I'm trying to make a custom input for currency in my app. I had those bootstrap wrappers and etc (I think it comes with simple_form or with bootstrap gem...), so, I could do something like:

<%= f.input :cost, wrapper => :append do %>
      <%= content_tag :span, "$", class: "add-on" %>
      <%= f.number_field :cost %>
<% end %>

And it works just as expected. The thing is: I need this same thing in a lot of places, and I don't want to copy/paste it all around.

So, I decided to create a custom input.

Until now, I got the following code:

class CurrencyInput < SimpleForm::Inputs::Base

  def input
    input_html_classes.unshift("string currency")
    input_html_options[:type] ||= input_type if html5?

    @builder.input attribute_name, :wrapper => :append do |b|
      # content_tag(:span, "$", class: "add-on")
      b.text_field(attribute_name, input_html_options)
    end
  end
end

But I got some errors. Looks like the b doesn't came as expected, so, it just don't work.

Is it really possible to do this? I could't find any example and can't make it work by myself.

Thanks in advance.

Answer

rafaelfranca picture rafaelfranca · Mar 14, 2013

That block variable is not existent, your input method have to be like this:

class CurrencyInput < SimpleForm::Inputs::Base

  def input
    input_html_classes.unshift("string currency")
    input_html_options[:type] ||= input_type if html5?

    template.content_tag(:span, "$", class: "add-on") +
      @builder.text_field(attribute_name, input_html_options)
  end
end

Now you can register a default wrapper to this custom input in you Simple Form initializer:

config.wrapper_mappings = { :currency => :append }

An you can use like this:

<%= f.input :cost, :as => :currency %>