Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying form error notifications within modal

I'm new to Rails and have been struggling with this issue for many hours - would really appreciate any help.

I have a signup form (using Devise and simple_form) inside a Bootstrap modal and would like error notifications to be displayed within the same modal when the form is submitted. Currently, when the form is submitted with errors, the page redirects to /users and the errors are rendered there. When the form is submitted without errors, the page stays on the home page and displays a 'success' flash message as desired.

I don't know whether this issue is caused by a controller/routing problem, whether I need to (first learn then) add in jQuery/Javascript/Ajax, or something else.

Modal code (contained in a 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
like image 268
Alex Yang Avatar asked Sep 06 '13 20:09

Alex Yang


People also ask

How to show message in modal?

If you want to display a message inside a modal you have to include (or inject) the modal markup in your page html, then you simply show/hide the modal via bootstrap functions.

How do I disable modal popup after form submission?

Show activity on this post. and write your html code in update panel then remove data-dismiss="modal" from the button. Hope it works for you.


1 Answers

You should add a :remote => true to your form, this causes the form to be submitted via Ajax. You then need to modify your controller to respond_to format.js. It should attempt to save the record. If there are errors, it should reply with create.js.erb which has something like the following in it:

$("#errors_div").html("<%= @resource.errors.full_messages %>")
like image 181
Jason Noble Avatar answered Sep 20 '22 20:09

Jason Noble