Display form error notifications in modal

I am new to Rails and have struggled with this problem for many hours - I will be very grateful for any help.

I have a registration form (using Devise and simple_form) inside the Bootstrap modal module and would like error notifications to be displayed in the same modal format when the form was submitted. Currently, when a form is submitted with errors, the page redirects / to users and errors are displayed there. When the form is submitted without errors, the page remains on the home page and displays a โ€œsuccessfulโ€ flash message as desired.

I donโ€™t know if this problem is caused by the controller / routing problem, do I need to (first find out) add jQuery / Javascript / Ajax or something else.

Modal code (contained in partial)

<div id="signupModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="signupLabel" aria-hidden="true"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">ร—</button> <h3 id="signupLabel">Sign up</h3> </div> <div class="modal-body"> <%= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name), html: {class: "form-horizontal"}) do |f| %> <%= f.error_notification %> <%= f.input :name, placeholder: 'John Smith', input_html: {class: 'span7'} %> ... <div class="form-actions"> <%= f.submit "Sign up", class: "btn btn-large btn-success" %> </div> <% end %> </div> </div> 

application_helper.rb - this code was added after reading this SO question

 module ApplicationHelper def resource_name :user end def resource @resource ||= User.new end def devise_mapping @devise_mapping ||= Devise.mappings[:user] end end 
+4
source share
2 answers

You must add :remote => true to your form, this will send the form via Ajax. Then you need to change your controller to respond_to format.js. He should try to save the record. If there are errors, it should answer create.js.erb , which has something like the following in it:

 $("#errors_div").html("<%= @resource.errors.full_messages %>") 
+8
source

If you look under the hood of simple_form, you will see that it adds new โ€œcssโ€ error classes and covers error messages based on evaluating the results of the @ model.errors array.

I do not think that the form is intended to handle the display of error messages when submitting via ajax. I think your options are:

  • Display the resulting form in a line on the server side via "render_to_string", and then replace the content on the page with the jQuery callback handler or by rendering the response as a js template.
  • Return the results as json, including @ model.errors, and then use this information in javascript to update the error message form.

I would start with option number 1, as this is a bit easier.

0
source

Source: https://habr.com/ru/post/1501003/


All Articles