simple_form custom input with custom wrapper

馋奶兔 提交于 2019-12-03 08:21:45

问题


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.


回答1:


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 %>


来源:https://stackoverflow.com/questions/15401199/simple-form-custom-input-with-custom-wrapper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!