将链接或按钮作为组件传递给SimpleForm包装器

时间:2016-03-22 13:49:23

标签: ruby forms ruby-on-rails-4 simple-form

我希望像这个模板一样重新定义输入:

<div class="form-group">
  <div class="input-group">
    <input class="form-control" type="text"> 
    <span class="input-group-btn"> 
      <button type="button" class="btn btn-primary" id="inline-button">Do Action!</button> 
      <!-- this could be a link or a button -->
    </span>
  </div>
</div>

我希望通过SimpleForm创建表单,将生成的按钮传递给简单的表单包装器,以便将其用作包装器中的组件:

<%= simple_form_for(something) do |form| %>
  <%= form.input :some_attribute, wrapper: "inline_button", button: "inline-button" %>
  <%= button_tag "inline-button" %>
<% end %>

(我知道这段代码不会起作用,它只是一个例子)

包装器将是:

config.wrappers "inline_button", tag: 'div', class: 'form-group' do |ib|
  ...
  ib.wrapper tag: 'div', class: 'input-group col-lg-10' do |ig| 
    ig.use :input, class: 'form-control'
    ig.wrapper tag: 'span', class: 'input-group-btn' do |btn|
      btn.use :button, class: 'btn btn-primary
    end
  end
end

1 个答案:

答案 0 :(得分:0)

解决。输入的工作方式如下:

<%= form.input :some_button, wrapper: "inline", inline_button:  link_to("Something", "#") %>

包装器:

config.wrappers "inline_button", tag: 'div', class: 'form-group' do |ib|
...
  ib.wrapper tag: 'div', class: 'input-group col-lg-10' do |ig| 
    ig.use :input, class: 'form-control'
    ig.wrapper tag: 'span', class: 'input-group-btn' do |btn|
      btn.use :button, class: 'btn btn-primary
    end
  end
end

然后,在config / initializers / simple_form / inline_button_component.rb

module SimpleForm
  module Components
    # Needs to be enabled in order to do automatic lookups
    module InlineElements
      # Name of the component method
      def inline_element(wrapper_options = nil)
        @inline_element ||= begin
          options[:inline_element].to_s.html_safe if options[:inline_element].present?
        end
      end

      # Used when the number is optional
      def has_inline_element?
        inline_element.present?
      end
    end
  end
end

SimpleForm::Inputs::Base.send(:include, SimpleForm::Components::InlineElements)