2016-01-15 35 views
0

我想創建一個自定義窗體幫助程序方法(用於自定義HTML複選框標記),並且我遇到了一些問題。我創建了下面的幫助,wrapped_check_box設置Rails自定義窗體幫助程序方法的麻煩

module FormHelper 
    class ActionView::Helpers::FormBuilder 
    include ActionView::Helpers::FormTagHelper 
    include ActionView::Helpers::FormOptionsHelper 

    def wrapped_check_box(name, options = {}) 
     raw "<div class='checkbox-wrapper'>" + \ 
     check_box_tag(@object_name, name, options) + \ 
     "<span class='checkbox-check'></span>" + \ 
     "</div>" 
    end 
    end 
end 

用法示例:

<%= f.wrapped_check_box :receives_updates %>

當我使用它,在這個例子中,從一個新的User模型,我得到下面的輸出:

<div class="checkbox-wrapper"> 
    <input type="checkbox" name="user" id="user" value="receives_updates" checked="checked"> 
    <span class="checkbox-check"></span> 
</div> 

這裏有兩個問題:

  1. 領域是自動選中的,甚至當我通過checked: false
  2. 這似乎是不正確的id值,這事情弄亂了<label>標籤,一切都在一般

我已經一直在關注各種文章,但很明顯我做錯了什麼。任何幫助表示讚賞:)

更新

我通過更新方法取得了一些進展:

check_box_tag("#{@object_name}[#{name.to_s}]", 1, options) 

現在輸出:

<input type="checkbox" name="user[receives_updates]" id="user_receives_updates" value="1" checked="checked"> 

這正是我想要的,但不幸的是,它仍然會輸出checked="checked",即使我將其作爲錯誤傳入。

任何想法?

+0

你對'id'的期望值是多少? – Abhinay

+0

@Abhinay一個普通的'f.check_box'輸出'user_receives_updates'作爲'id',這是正確的值 –

回答

0

我又回到了的文檔,並對它進行了更多的瞭解。我結束了這是怎麼回事:

module FormHelper 
    def wrapped_check_box_tag(name, value=1, checked=false, options={}) 
    raw "<div class='checkbox-wrapper'>" + \ 
     check_box_tag(name, value, checked, options) + \ 
     "<span class='checkbox-checks'></span>" + \ 
    "</div>" 
    end 

    class ActionView::Helpers::FormBuilder 
    include FormHelper 
    include ActionView::Helpers::FormTagHelper 
    include ActionView::Helpers::FormOptionsHelper 

    def wrapped_check_box(name, options = {}) 
     wrapped_check_box_tag("#{@object_name}[#{name.to_s}]", options[:value], options[:checked], options) 
    end 
    end 
end 

現在,這使得全球的方法,以及現有的形式幫助:

<%= wrapped_check_box_tag :accepts_terms %>

<%= f.wrapped_check_box :receives_updates, { checked: true } %>

如果任何人有任何建議,我全是耳朵!