gpt4 book ai didi

html - 简单形式 : disable form without adding disabled: true or readonly: true to every input

转载 作者:太空狗 更新时间:2023-10-29 15:28:14 24 4
gpt4 key购买 nike

我有一个大型 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 代码在整个表单中快速切换禁用只读表单属性?

最佳答案

您可以像这样创建一个禁用输入的自定义包装器:

# 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

关于html - 简单形式 : disable form without adding disabled: true or readonly: true to every input,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27285639/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com