【问题标题】:simple_form: disable form without adding disabled: true or readonly: true to every inputsimple_form: 禁用表单而不添加 disabled: true 或 readonly: true 到每个输入
【发布时间】:2015-02-01 20:06:07
【问题描述】:

我有一个大型 simple_form 表单,其中的字段需要启用禁用,具体取决于表单的部分加载位置。

我的问题是:如何使用 simple_form 帮助器/包装器快速禁用每个表单输入

Simple Form's documentation 解释了如何使用disabled: true 禁用单个输入字段

<%= simple_form_for @user do |f| %>
  <%= f.input :username, disabled: true %>
  <%= f.button :submit %>
<% end %>

但文档不太清楚我如何通过 simple_form 帮助程序禁用整个表单,而无需在实际上每个表单输入上重复disabled: true

我尝试将 disabled: truereadonly: true 传递给 simple_form 的 :wrapper_mappings 选项,但这不起作用。


示例代码:

我通过部分加载表单来定义 simple_form 显示变量。这有效:

#user/show.html.erb:
<%= render partial: 'shared/form', locals: {questionnaire: @questionnaire, readonly_state: true, disabled_state: true, bootstrap_form_class: 'form-horizontal'} %>

但是,readonly_statedisabled_state 不起作用,除非我将它们传递给每个表单输入:

# shared/_form.html.erb
<%= simple_form_for(@questionnaire, :html => {:class => bootstrap_form_class}, 

:wrapper_mappings => {check_boxes: :vertical_radio_and_checkboxes, file: :vertical_file_input,
boolean: :vertical_boolean  }) do |f| %>

  <%= f.input :username, disabled: disabled_state, hint: 'You cannot change your username.' %>
  <%= f.input :email, disabled: disabled_state %>
  <%= f.input :city, disabled: disabled_state %>
  <%= f.input :country, disabled: disabled_state %>
  . . .
  <%= f.button :submit %>
<% end %>

您可以快速看到大型表格的重复性。

如何使用 DRY 代码在整个表单中快速切换 disablereadonly 表单属性?

【问题讨论】:

    标签: html ruby-on-rails forms simple-form disabled-input


    【解决方案1】:

    您可以使用 CSS 来模拟 disabled 属性。 只需创建类并有条件地添加它。

    .disable {
      background: #f2f2f2;
      pointer-events:none;
    }
    

    【讨论】:

    • disabled 属性相比,此输入将被提交并参与客户端表单验证。
    【解决方案2】:

    有趣:

    <%= f.input :username, disabled: true %>
    

    为元素生成“禁用”类。

    <%= f.input :username, input_html: {disabled: true} %>
    

    不要这样做:)

    但你可以这样做:

    <%= f.input :username, input_html: {readonly: :true} %>
    

    <%= f.input :username, input_html: {disabled: :true} %>
    

    在哪里(与只读不同)光标变为?

    【讨论】:

      【解决方案3】:

      您可以创建一个禁用输入的自定义包装器,如下所示:

      # config/initializers/simple_form.rb
      config.wrappers :disabled_form do |b|
        b.use :input, disabled: true, readonly: true
      end
      

      并在表格中使用:

      <%= simple_form_for @model, wrapper: :disabled_form %>
        <%= f.input :field %>
        ...
      <% end %>
      

      根据表单中不同输入的数量,您可能需要创建更多自定义包装器并在禁用表单中使用wrapper_mapping

      【讨论】:

        【解决方案4】:

        只是一个建议,您可以通过设置 $('.form input').prop('disabled', true); 来实现使用 jquery 的行为,其中 form 是您的表单类。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-12-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-11-21
          相关资源
          最近更新 更多