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.
I'm using the 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? The customer_id
is required in the model, so I need the form to tell the user that if they leave it blank.
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):
<%= 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). Basically, you can use that to append whatever markup you want to your f.input
. I did the following, which is pretty hacky, but it does what I need it to do:
<%= 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. Hope this helps someone in the future!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With