情况
有一个简单的形式,我将其抽象部分发布在下面:
<div class="form-group">
<%= f.label :net %>
<div class="input-group w-50">
<%= f.text_field :net,
required: true,
class: 'form-control text-right' %>
<div class="input-group-append">
<span class="input-group-text" style="width: 40px;">€</span>
</div>
</div>
</div>
&
<div class="form-group">
<%= f.label :vat_rate, t('in_invoice.form.vat_rate') %>
<%= render 'home/shared/standard_vat' %>
<div class="input-group w-50">
<%= f.text_field :vat_rate,
required: true,
class: 'form-control text-right' %>
<div class="input-group-append">
<span class="input-group-text" style="width: 40px;">%</span>
</div>
</div>
</div>
型号:
...
validates :net, :number, :vat_rate, presence: true
validates :net, numericality: { greater_than: 0}
validates :vat_rate, numericality: { only_integer: true, greater_than_or_equal_to: 0}
validates :net, numericality: true
...
我的问题 我想在表单中的
vat_rate
(屏幕截图:“增值税税率(%)”)标签上添加一个星号。但由于某种原因,它只出现在 :net
和 :number
字段上,尽管它们相等(例如删除中间的部分,包括存在验证),如屏幕截图中所示。 (我认为这并不重要,但形式是用 simple_form
初始化的 simple_form_for
)
星号是通过简单的形式添加的。当您传递文本作为第二个参数时,您会覆盖所有内容。如果您想保留
*
传递文本作为选项:
<%= f.label :vat_rate, label: t('in_invoice.form.vat_rate') %>
# ^^^^^^
https://github.com/heartcombo/simple_form/blob/v5.3.0/lib/simple_form/form_builder.rb#L319
如果您的
simple_form
看起来不像这样,那么您就错过了简单形式的要点:
<%= simple_form_for @invoice do |f| %>
<%= f.input :net %>
<%= f.input :vat_rate %>
<% end %>
您应该只配置一次输入并仅使用
input
助手:
https://github.com/heartcombo/simple_form/tree/main#configuration
例如:
# config/initializers/simple_form.rb
module InputGroup
def append(wrapper_options = nil)
template.content_tag(:span, options[:append], class: "input-group-text")
end
end
SimpleForm.include_component(InputGroup)
SimpleForm.setup do |config|
# https://github.com/heartcombo/simple_form-bootstrap
config.wrappers :group, tag: "div", class: "form-group", error_class: "form-group-invalid", valid_class: "form-group-valid" do |b|
b.use :html5
b.use :placeholder
b.optional :maxlength
b.optional :minlength
b.optional :pattern
b.optional :min_max
b.optional :readonly
b.use :label
b.wrapper :input_group_tag, tag: "div", class: "input-group-append" do |ba|
ba.use :input, class: "form-control", error_class: "is-invalid", valid_class: "is-valid"
ba.optional :append
end
b.use :full_error, wrap_with: {tag: "div", class: "invalid-feedback d-block"}
b.use :hint, wrap_with: {tag: "small", class: "form-text text-muted"}
end
end
<%= simple_form_for @invoice do |f| %>
<%= f.input :net, wrapper: :group, append: "€" %>
<%= f.input :vat_rate, wrapper: :group, append: "%" %>
<% end %>