Adding a method to FormBuilder that calls a helper method that renders a partial

前端 未结 1 1586
生来不讨喜
生来不讨喜 2021-02-10 08:50

So I\'ve got this helper method, right?

def table_form_field(name_or_options = nil, *args, &block)
  # ...
  render :partial => \"snippets/table_form_fiel         


        
1条回答
  •  南旧
    南旧 (楼主)
    2021-02-10 09:27

    You can access an instance variable called @template from within form builders so you can just call table_form_field on the @template variable.

    For example, I would create a custom form builder that inherits from ActionView::Helpers::FormBuilder

    class MyFormBuilder < ActionView::Helpers::FormBuilder
      def table_form_field(*attrs, &block)
        @template.table_form_field(*attrs, &block)
      end
    end
    

    Then in your form_for you can tell it to use your custom form builder

    <%= form_for @myobject, :builder => MyFormBuilder do |f| %>
      <%= f.table_form_field :myfield do %>
      <% end %>
    <%= end %>
    

    0 讨论(0)
提交回复
热议问题