Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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 %>
like image 833
Nathan Wallace Avatar asked Oct 31 '13 02:10

Nathan Wallace


1 Answers

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!

like image 78
Nathan Wallace Avatar answered Nov 15 '22 07:11

Nathan Wallace