简体   繁体   中英

Rails 4: Custom form builder checkbox

I have a form builder helper method:

 def check_box(attribute_name, *args)
    @template.content_tag 'label', class: 'checkbox', for: "#{@object_name}_#{attribute_name}" do
      super(attribute_name, *args) + @template.content_tag('i') +
          @object.class.human_attribute_name(attribute_name)
    end
  end

This generates a nested HTML as:

<label class="checkbox" for="application_setting_alert_on_click_link">
<input type="hidden" value="0" name="application_setting[alert_on_click_link]">
<input id="application_setting_alert_on_click_epay_link" type="checkbox" value="1" name="application_setting[alert_on_click_link]">
<i></i>
When customer visits link
</label>

But by W3C validator we cannot have 2 inputs inside a label hence, I want the hidden input to be taken out and placed outside the label as:

<input type="hidden" value="0" name="application_setting[alert_on_click_link]">
<label class="checkbox" for="application_setting_alert_on_click_link">
    <input id="application_setting_alert_on_click_epay_link" type="checkbox" value="1" name="application_setting[alert_on_click_link]">
    <i></i>
    When customer visits link
 </label>

Any help?

Not an easy live with those check_boxes. You need to tell rails not to include the hidden field and add it by yourself (not tested):

  def check_box(attribute_name, *args)
    hidden_field attribute_name, value: 0, id: false
    @template.content_tag 'label', class: 'checkbox', for: "#{@object_name}_#{attribute_name}" do
      options = args.extract_options!
      options[:include_hidden] = false
      args << options
      super(attribute_name, *args) + @template.content_tag('i') +
          @object.class.human_attribute_name(attribute_name)
    end
  end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM