[英]Simple_Form display validation error messages next to different input field
I have a form that allows the user to search for existing records to populate an association. 我有一个表单,允许用户搜索现有记录来填充关联。 Each "Booking" belongs to a "Customer". 每个“预订”属于“客户”。 So the form allows you type the customer's name, it does a search automatically, and you click the customer you want. 因此,表单允许您键入客户的名称,它会自动搜索,并单击您想要的客户。 The input field you're typing into should display the customer's name, but for the form to work, I set the customer_id
in a hidden input field. 您输入的输入字段应显示客户的名称,但为了使表单生效,我将customer_id
设置为隐藏的输入字段。
I'm using the simple_form gem. 我正在使用simple_form gem。 Does anybody know if I can display the validation errors for the customer_id
next to the text input field that displays the customer's name? 有谁知道我是否可以显示该验证错误customer_id
旁边显示客户的名称的文本输入字段? The customer_id
is required in the model, so I need the form to tell the user that if they leave it blank. customer_id
在模型中是必需的,因此我需要表单告诉用户他们是否留空。
View code (simplified -- there's some JavaScript that handles searching when you type into the customer text box, and that sets the value in the hidden field to the customer's id when you make a selection): 查看代码(简化 - 当您键入客户文本框时,会有一些JavaScript处理搜索,并且在您进行选择时将隐藏字段中的值设置为客户的ID):
<%= simple_form_for @booking do |f| %>
<%= f.hidden_field :customer_id, id: "customer_id" %>
<%= f.input :customer, required: true,
input_html: { value: @booking.customer_name } %>
<% end %>
I eventually found out about the append
block in simple_form ( buried in a pull request , not documented anywhere else that I could find). 我最终发现了simple_form中的append
块( 埋没在pull请求中 ,没有在我能找到的任何其他地方记录)。 Basically, you can use that to append whatever markup you want to your f.input
. 基本上,您可以使用它将您想要的任何标记附加到f.input
。 I did the following, which is pretty hacky, but it does what I need it to do: 我做了以下,非常hacky,但它做我需要做的事情:
<%= f.input :customer, required: true,
wrapper_html: { class: ("error" if @booking.errors[:customer_id].any?) } do %>
<%= f.input_field :customer, value: @booking.customer_name %>
<%= f.error :customer_id %>
<% end %>
First, I had to conditionally add the class "error" to the wrapper if there were any errors on the related field, then I used the append
block to render out the input field, followed by the errors for the related field from the model. 首先,如果相关字段上有任何错误,我必须有条件地将类“错误”添加到包装器中,然后我使用append
块渲染输入字段,然后是模型中相关字段的错误。 Hope this helps someone in the future! 希望这有助于未来的人!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.