Default disable_with for simple_form submit

落花浮王杯 提交于 2019-12-05 06:01:05

This is a little different in newer versions of Rails, as setting the property disable_with is deprecated. I wrote an article on this: http://www.railsonmaui.com/blog/2014/02/23/simple-form-and-disable-processing-by-default/

Here's the new code:

SimpleForm::FormBuilder.class_eval do
  def submit_with_override(field, options = {})
    data_disable_with = { disable_with: 'Processing...' }
    options[:data] = data_disable_with.merge(options[:data] || {})
    submit_without_override(field, options)
  end
  alias_method_chain :submit, :override
end

And thanks to @Appster for the idea!

Adding this override to my simple_form.rb worked like a charm!

SimpleForm::FormBuilder.class_eval do
  def submit_with_override(field, options = {})
    submit_without_override(field, {:disable_with => 'saving...'}.merge(options))
  end
  alias_method_chain :submit, :override
end

According to ActionView::Helpers::FormBuilder.submit, f.button accespts 1~2 parameters, so both of following codes should be worked.

  • f.submit "MyText", class: "my-btn"
  • f.submit class: "my-btn"

In my case, adding this codes to initialize file worked fine.

SimpleForm::FormBuilder.class_eval do
  def submit_with_override(value=nil, options={})
    value, options = nil, value if value.is_a?(Hash)
    data_disable_with = { disable_with: 'Processing...' }
    options[:data] = data_disable_with.merge(options[:data] || {})
    submit_without_override(value, options)
  end
  alias_method_chain :submit, :override
end

Hope it helps.

It didn't override any existing data- attributes on the submit button which is compatible with Rails 5.

module DisableDoubleClickOnSimpleForms
  def submit(field, options = {})
    if field.is_a?(Hash)
      field[:data] ||= {}
      field[:data][:disable_with] ||= field[:value] || 'Processing...'
    else
      options[:data] ||= {}
      options[:data][:disable_with] ||= options[:value] || 'Processing...'
    end
    super(field, options)
  end
end

SimpleForm::FormBuilder.prepend(DisableDoubleClickOnSimpleForms)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!