每天一剂Rails良药之Creating a Custom Form Builder

有时候我们希望我们的表单拥有一致的显示风格,今天我们就看看用Rails怎样创建一个Helper来自定义表单。

1,实现自己的FormBuilder
在app/helpers/application_helper.rb里加入以下代码:
class TabularFormBuilder < ActionView::Helpers::FormBuilder
    (field_helpers - %w(check_box radio_button)).each do |selector|
      src = <<-END_SRC
        def #{selector}(field, options = {})
          @template.content_tag("tr",
            @template.content_tag("td", field.to_s.humanize + ":") +
              @template.content_tag("td", super))
        end
      END_SRC
      class_eval src, __FILE__, __LINE__
    end
end

def tabular_form_for(name, object = nil, options = nil, &proc)
    concat("<table>", proc.binding)
    form_for(name,
             object,
             (options||{}).merge(:builder => TabularFormBuilder),
             &proc)
    concat("</table>", proc.binding)
end

这里我们创建了tabular_form_for这个helper方法供页面使用,这里:builder => TabularFormBuilder用来生成一个table格式的表单。

2,在页面中使用自定义表单helper方法
<% tabular_form_for :contact do |f| %>
    <%= f.text_field :name %>
    <%= f.text_field :email %>
    <%= f.text_field :phone %>
<% end %>

就这么简单!
让我们来给form table隔行加上背景色:
class TabularAlternatingColorFormBuilder < ActionView::Helpers::FormBuilder
  (field_helpers - %w(check_box radio_button)).each do |selector|
    src = <<-END_SRC
      def #{selector}(field, options = {})
        @template.content_tag("tr",
          @template.content_tag("td", field.to_s.humanize + ":") +
          @template.content_tag("td", super),
            :class => (@alt = (@alt ? false : true)) ? "alt-row" : ""  )
      end
    END_SRC
    class_eval src, __FILE__, __LINE__
  end
end

def tabular_form_with_alternating_colors_for(name, object = nil, options = nil, &proc)
    concat("<table>", proc.binding)
    form_for(name,
             object,
             (options||{}).merge(:builder => TabularAlternatingColorFormBuilder),
             &proc)
    concat("</table>", proc.binding)
end

修改default.css:
.alt-row {
  background: #fab444;
}

页面调用:
<%= stylesheet_link_tag "default" %>

<% tabular_form_with_alternating_colors_for :contact do |f| %>
    <%= f.text_field :name %>
    <%= f.text_field :email %>
    <%= f.text_field :phone %>
<% end %>

你可能感兴趣的:(Web,css,F#,脚本,Rails)