Reputation: 155
I have a modal, but when I close the modal I need to show a flash message to verify that the action was performed, the moment I have this code, but I cant get it, I'm using Foundation but Foundation doesn't have "Toast" or "Alert" like Materialize or Bootstrap, here is my code:
layouts/alerts.html.erb
<% if notice %>
<div class="callout small notice">
<%= notice %>
</div>
<% end %>
<% if alert %>
<div class="callout small alert">
<%= alert %>
</div>
<% end %>
contact_form.html.erb
<div class="callout">
<h6>Formulario de contacto</h6>
<%= form_for @contact, remote: true, authenticity_token: true do |f| %>
<% if @contact.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@contact.errors.count, "error") %> prohibited this @contact from being saved:</h2>
<ul>
<% @contact.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.text_field :title, placeholder: "Title" %>
</div>
<div class="field">
<%= f.text_area :content, placeholder: "Content", :rows => 10, :cols => 120 %>
</div>
<div class="actions">
<%= f.submit "Send", class: "button" %>
</div>
<% end %>
</div>
create.js.erb
<% if @contact.errors.empty? %>
$('#exampleModal1').foundation('close');
$(".notice").html('<%= j render partial: "layouts/alerts" %>');
<% else %>
$(".alert").html('<%= j render partial: "layouts/alerts" %>');
<% end %>
contact_controller.rb
def create
@contact = Contact.new(contact_params)
@contact.email = current_enterprise.email
respond_to do |format|
if @contact.save
ContactMailer.contact_email(@contact).deliver
format.html { redirect_to root_path, notice: 'Contact was successfully created.' }
format.js { flash[:notice] = "The message was sent" }
format.json { render :show, status: :created, location: @contacts }
else
format.html { render :new }
format.json { render json: @contact.errors, status: :unprocessable_entity }
end
end
end
Upvotes: 1
Views: 4201
Reputation: 121
I was already using toastr so for me it was as simple as this:
# create.js.erb
toastr['info']('<%= j @notice %>');
Upvotes: 0
Reputation: 12653
No doubt you have already solved this, but for anyone else who ends up here via Google:
Your code should work, but you need to pass notice
or alert
to your alerts.html.erb
partial.
#create.js.erb
<% if @contact.errors.empty? %>
$('#exampleModal1').foundation('close');
$(".notice").html('<%= j render partial: "layouts/alerts", locals: { notice: flash[:notice] } %>');
<% else %>
$(".alert").html('<%= j render partial: "layouts/alerts", locals: { alert: flash[:alert] } %>');
<% end %>
You may also need to set a value for flash[:alert]
in your controller for unsuccessful saves.
Upvotes: 1