2012-09-03 28 views
14

我使用sorcery進行身份驗證以及twitter bootstrap如何更改默認導軌錯誤分區「field_with_errors」

我想通過更改添加到DOM的默認導軌<div class="field_with_errors">來在我的註冊表單中設置我的錯誤消息的樣式。

什麼是這樣做的軌道公約?

我想你可以添加一些JavaScript來操縱DOM重命名<div class="field_with_errors">,但這似乎是一個黑客攻擊。似乎應該有一種方法來覆蓋這在軌道,但我不知道在哪裏做的。

這是自舉如何要求您將錯誤使用其內置的形狀誤差風格標記:

<div class="control-group error"> 
    <label class="control-label" for="inputError">Input with error</label> 
    <div class="controls"> 
    <input type="text" id="inputError"> 
    <span class="help-inline">Please correct the error</span> 
    </div> 
</div> 
+0

我認爲你正在尋找這個
HTTP ://stackoverflow.com/questions/5267998/rails-3-field-with-errors-wrapper-changes-the-page-appearance-how-to-avoid-t – Prem

+0

@prem:謝謝!即將鏈接到我自己。 –

回答

24

從上面的鏈接,如果你把下面的內部class Application < Rails::Applicationconfig/application.rb

config.action_view.field_error_proc = Proc.new { |html_tag, instance| 
    "<div class=\"field_with_errors control-group error\">#{html_tag}</div>".html_safe 
} 

每當驗證失敗時,您的輸入標籤周圍都會有一個紅色標記

+4

這會導致在標籤的表單水平方向上使輸入跳到一行,是否有解決方法? – Nayish

+0

我改變了單個動作的行爲,添加了一些受到ActionView :: Base.field_error_proc = Proc.new {| html_tag,instance | 「

#{html_tag}
」.html_safe}'在特定的操作方法中。 [參考文獻](http://stackoverflow.com/a/11157784/664833) – user664833

1

對於Bootstrap 3.2,您可以使用某物。像這樣(加nokogiri寶石您的Gemfile):

ActionView::Base.field_error_proc = Proc.new do |html_tag, instance| 
    html = %(<div class="field_with_errors">#{html_tag}</div>).html_safe 
    # add nokogiri gem to Gemfile 

    form_fields = [ 
    'textarea', 
    'input', 
    'select' 
    ] 

    elements = Nokogiri::HTML::DocumentFragment.parse(html_tag).css "label, " + form_fields.join(', ') 

    elements.each do |e| 
    if e.node_name.eql? 'label' 
     html = %(<div class="control-group has-error">#{e}</div>).html_safe 
    elsif form_fields.include? e.node_name 
     if instance.error_message.kind_of?(Array) 
     html = %(<div class="control-group has-error">#{html_tag}<span class="help-block">&nbsp;#{instance.error_message.uniq.join(', ')}</span></div>).html_safe 
     else 
     html = %(<div class="control-group has-error">#{html_tag}<span class="help-block">&nbsp;#{instance.error_message}</span></div>).html_safe 
     end 
    end 
    end 
    html 
end 

將此代碼裏面config/initializers/field_error_proc.rb文件(創建一個如果不存在的話)

這是稍微修改從代碼:Overriding ActionView::Base.field_error_proc in Rails

0

注意,如果您正在使用SimpleForm,在application.rb中使用Proc的接受答案將不起作用。相反,您應該編輯simple_form初始值設定項。例如使用引導3.2:on Rails的5

config.wrappers :default, class: :input, 
    hint_class: :field_with_hint, error_class: :'has-error' do |b| 
    [...] 
    b.use :hint, wrap_with: { tag: :span, class: :'text-warning' } 
    b.use :error, wrap_with: { tag: :span, class: :'text-danger' } 
end 
1

Twitter的引導3.3.6,這正好在初始化customize_error.rb和工作對我來說:

ActionView::Base.field_error_proc = proc { |html_tag, _instance| "<div class=\"has-error\">#{html_tag}</div>".html_safe }