How to open a bootstrap modal using rails link_tag and remote: true - ruby-on-rails-3

I am usinge rails 5.0.2
My view page code is:
<%= link_to 'Download files',cader_history_path(:job_id => #check_cader[0].job_id), :remote => true, class: "btn btn-link", 'data-toggle' => 'modal', 'data-target' => '#files' %>
But its did not open the modal, after making this call as remote: true
Is their any other way round thanks in advance

As per the description mentioned in the post and code posted, it seems like you have made jquery selector in the html tag
<%= link_to 'Download files',cader_history_path(:job_id => #check_cader[0].job_id), :remote => true, class: "btn btn-link", 'data-toggle' => 'modal', 'data-target' => '#files' %>
Modify it to
<%= link_to 'Download files',cader_history_path(:job_id => #check_cader[0].job_id), :remote => true, class: "btn btn-link", 'data-toggle' => 'modal', 'data-target' => 'files' %>
In the above code the files is the id of the modal so no need to append "#" in front of it.

1- Add a generic modal to your layout with i.e #defaultModal id.
2- In your controller js.erb response file, find that modal and replace its content with your html content and show modal.
js.erb file
$('#defaultModal .modal-footer').remove();
$('#defaultModal .modal-body').remove();
$('#defaultModal form').remove();
$('#dynamic-content').html('<%= escape_javascript(render :template => "#{target}", :formats => [:html], :handlers => [:erb]) %>'); //this contains both footer and body
$('#defaultModal .modal-header h4').text('<%= #title %>');
$('.other-modals').modal('hide');
$('#defaultModal').modal('show');
default modal html file
<div class="modal fade" id="defaultModal" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 id="default-modal-header">.</h4>
</div>
<div id="dynamic-content">
<div id="default-modal-body" class="modal-body">
<p class='loading'>Loading...</p>
</div>
<div id="default-modal-footer" class="modal-footer">
<%= link_to 'Close', "#", "data-dismiss" => "modal", :class => "btn", "aria-hidden" => true %>
</div>
</div>
</div>
</div>
</div>

Related

Wicked_PDF does not download when I switch to using form_with instead of form_tag

I noticed a bug with my view where my form could not be submitted after the initial submission to generate a PDF, and during research saw that form_with was the recommended way to build forms going forward with rails. I updated my form, and everything seems to be working the way it's supposed to, but now the PDF doesn't download as before and just seems to render the string in a response without generating the file. Using Wicked-PDF and Rails 5.2.1. Sorry if I'm missing something super obvious!
Using form_tag (pdf downloads as expected):
form in view:
<%= form_tag("download_pdf", format: :pdf, method: "get") do %>
<div class="input-group mb-3">
<%= collection_select(:location, :id, Location.all, :id, :name, {:include_blank => 'Filter by location'}, {:id => 'qr_code_loc_select', :selected_value => '', :name => 'location', :style=> 'width: 17em', :autocomplete => 'off'}) %>
</div>
<div class="input-group mb-3">
<%= collection_select(:name, :id, DeviceType.all, :id, :name, {:include_blank => 'Filter by device type'}, {:id => 'qr_device_type_select', :selected_value => '', :name => "device_type", :style=> 'width: 17em', :autocomplete => 'off'}) %>
</div>
<div class="input-group mb-3">
<input type="number" name="width" class="form-control label_size_input" id="label_width" step="0.001" placeholder="Label Width" autocomplete ='off' aria-describedby="basic-addon3">
<div class="input-group-append">
<span class="input-group-text">inches</span>
</div>
</div>
<div class="input-group mb-3">
<input type="number" name="height" class="form-control label_size_input" id="label_height" step="0.001" placeholder="Label Height" autocomplete ='off' aria-describedby="basic-addon3">
<div class="input-group-append">
<span class="input-group-text">inches</span>
</div>
</div>
<%= label_tag "qr_col", "Columns:", class:"ml-2 text-light" %>
<div class="input-group mb-3">
<%= select_tag "qr_col", options_for_select(["1","2", "3", "4", "5"], "3"), {:autocomplete => 'off'}%>
</div>
<%= label_tag "paper_size", "Paper Size:", class:"ml-2 text-light" %>
<div class="input-group mb-3">
<%= select_tag "paper_size", options_for_select(#paper_size, "A4"), {:autocomplete => 'off'}%>
</div>
<div class="btn-group mb-3" role="group" aria-label="pdf_export_button" id="pdf_export">
<%= hidden_field_tag :column_number %>
<%= hidden_field_tag :label_size %>
<%= hidden_field_tag :format, "pdf" %>
<%= submit_tag("Create PDF Document", {:class=> "btn btn-secondary"}) %>
<% end %>
</div>
in controller:
def download_pdf
#columns = params[:column_number].to_i
#height = params[:height]
#width = params[:width]
#paper_size = params[:paper_size]
#type = params[:device_type]
#location = params[:location]
if #type.blank?
if #location.blank?
#devices = Device.all
else
#devices = get_devices_by_location(#location)
end
else
if #location.blank?
#devices = Device.where('device_type_id=?', #type)
else
#devices = get_devices_by_type_and_location(#type, #location)
end
end
pdf_string = render_to_string(
template: "qr_codes/show.html.erb",
layout: "layouts/pdf_layout.pdf.erb",
viewport_size: '1280x1024',
page_size: #paper_size
)
respond_to do |format|
format.pdf do
pdf = WickedPdf.new.pdf_from_string(pdf_string)
send_data pdf, :filename => "report.pdf", :type => "application/pdf"
end
end
end
in console:
Started GET "/qr_codes/download_pdf?utf8=%E2%9C%93&location=&device_type=&width=&height=&qr_col=3&paper_size=A4&column_number=3&label_size=&format=pdf&commit=Create+PDF+Document" for 127.0.0.1 at 2018-11-14 20:03:51 -0500
Processing by QrCodesController#download_pdf as PDF
Parameters: {"utf8"=>"✓", "location"=>"", "device_type"=>"", "width"=>"", "height"=>"", "qr_col"=>"3", "paper_size"=>"A4", "column_number"=>"3", "label_size"=>"", "commit"=>"Create PDF Document"}
Rendering qr_codes/show.html.erb within layouts/pdf_layout.pdf.erb
(0.4ms) SELECT COUNT(*) FROM "devices"
Device Load (0.6ms) SELECT "devices".* FROM "devices"
Rendered qr_codes/show.html.erb within layouts/pdf_layout.pdf.erb (778.0ms)
"***************[\"/Users/joe/.rbenv/versions/2.5.0/bin/wkhtmltopdf\", \"-q\", \"file:////var/folders/pf/kl12j8g91w5bj7ssc_0fdv3c0000gn/T/wicked_pdf20181114-912-1opkhpt.html\", \"/var/folders/pf/kl12j8g91w5bj7ssc_0fdv3c0000gn/T/wicked_pdf_generated_file20181114-912-m57i12.pdf\"]***************"
Rendering text template
Rendered text template (0.1ms)
Sent data report.pdf (1.7ms)
Completed 200 OK in 3077ms (Views: 1.2ms | ActiveRecord: 1.0ms)
Using form_with (pdf does not generate as expected and only has an unformatted string in response):
form in view:
<%= form_with url: download_pdf_path(format: :pdf), method: "get" do |f| %>
<div class="input-group mb-3">
<%= f.collection_select(:id, Location.all, :id, :name, {:include_blank => 'Filter by location'}, {:id => 'qr_code_loc_select', :selected_value => '', :name => 'location', :style=> 'width: 17em', :autocomplete => 'off'}) %>
</div>
<div class="input-group mb-3">
<%= f.collection_select(:id, DeviceType.all, :id, :name, {:include_blank => 'Filter by device type'}, {:id => 'qr_device_type_select', :selected_value => '', :name => "device_type", :style=> 'width: 17em', :autocomplete => 'off'}) %>
</div>
<div class="input-group mb-3">
<%= f.number_field nil, {:name => "width", :id => "label_width", :class => "form-control label_size_input", :step => "0.001", :placeholder => "Label Width", :autocomplete => 'off'} %>
<div class="input-group-append">
<span class="input-group-text">inches</span>
</div>
</div>
<div class="input-group mb-3">
<%= f.number_field nil, {:name => "height", :id => "label_height", :class => "form-control label_size_input", :step => "0.001", :placeholder => "Label Height", :autocomplete => 'off'} %>
<div class="input-group-append">
<span class="input-group-text">inches</span>
</div>
</div>
<%= label_tag "qr_col", "Columns:", class:"ml-2 text-light" %>
<div class="input-group mb-3">
<%= f.select "column_number", options_for_select(["1","2", "3", "4", "5"], "3"), {:autocomplete => 'off'}, :id => "qr_col"%>
</div>
<%= label_tag "paper_size", "Paper Size:", class:"ml-2 text-light" %>
<div class="input-group mb-3">
<%= f.select "paper_size", options_for_select(#paper_size, "A4"), {:autocomplete => 'off'}%>
</div>
<div class="btn-group mb-3" role="group" aria-label="pdf_export_button" id="pdf_export">
<%= f.hidden_field :label_size %>
<%= f.submit("Create PDF Document", {:class=> "btn btn-secondary", :data => { turbolinks: false }}) %>
</div>
<% end %>
controller:
def download_pdf
#columns = params[:column_number].to_i
#height = params[:height]
#width = params[:width]
#paper_size = params[:paper_size]
#type = params[:device_type]
#location = params[:location]
if #type.blank?
if #location.blank?
#devices = Device.all
else
#devices = get_devices_by_location(#location)
end
else
if #location.blank?
#devices = Device.where('device_type_id=?', #type)
else
#devices = get_devices_by_type_and_location(#type, #location)
end
end
respond_to do |format|
format.pdf do
pdf = WickedPdf.new.pdf_from_string(
render_to_string(
template: 'qr_codes/show.html.erb',
layout: 'layouts/pdf_layout.pdf.erb',
page_size: #paper_size
),
)
send_data pdf, :filename =>'PDF Report-' + Time.now.strftime('%v %H:%M:%S').to_s, disposition: 'attachment', :type => "application/pdf"
end
end
end
in console:
Started GET "/qr_codes/download_pdf_path?utf8=%E2%9C%93&location=&device_type=&width=&height=&column_number=3&paper_size=A4&label_size=&format=pdf&commit=Create%20PDF%20Document" for 127.0.0.1 at 2018-11-14 20:01:04 -0500
Processing by QrCodesController#download_pdf as PDF
Parameters: {"utf8"=>"✓", "location"=>"", "device_type"=>"", "width"=>"", "height"=>"", "column_number"=>"3", "paper_size"=>"A4", "label_size"=>"", "commit"=>"Create PDF Document"}
Rendering qr_codes/show.html.erb within layouts/pdf_layout.pdf.erb
(0.3ms) SELECT COUNT(*) FROM "devices"
Device Load (1.2ms) SELECT "devices".* FROM "devices"
Rendered qr_codes/show.html.erb within layouts/pdf_layout.pdf.erb (453.5ms)
"***************[\"/Users/joe/.rbenv/versions/2.5.0/bin/wkhtmltopdf\", \"-q\", \"file:////var/folders/pf/kl12j8g91w5bj7ssc_0fdv3c0000gn/T/wicked_pdf20181114-912-1ym4a9q.html\", \"/var/folders/pf/kl12j8g91w5bj7ssc_0fdv3c0000gn/T/wicked_pdf_generated_file20181114-912-edkha0.pdf\"]***************"
Rendering text template
Rendered text template (0.1ms)
Sent data PDF Report-14-NOV-2018 20:01:07 (1.6ms)
Completed 200 OK in 2682ms (Views: 1.1ms | ActiveRecord: 1.5ms)
IT WAS SOMETHING DUMB--decided to turn my attention to the form_with documentation and found out that remote: true is set by default. If you set this to local: true, the issue is resolved. Hope that helps someone else!

Rails create new entry via bootstrap modal (or similarly with lightbox)

I would like to include in a new page a modal that can create "on the fly" an entry of another model and refresh a select with new entry without refreshing the page.
The first attemp I do is something like this:
The page that raise the modal (ok, it raises correctly the form of the other model)
#new.html.erb
<%= simple_form_for(#odl) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.collection_select :client_id, Client.order("LOWER(last_name) ASC"), :id, :last_name_and_name_and_company, :prompt => "Select a client" %>
Create new client
#...some code...
#...and the modal that raise correctly
<div id="client_modal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="client_modal_label" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="client_modal_label">Create a new client</h3>
</div>
<div class="modal-body">
<% #client = Client.new %>
<%= render :partial => "clients/form" %>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary">Create Client</button>
</div>
</div>
I would like that if some input in the new client form are wrongs, it appears on the fly in the modal and not in a new "classic" page.
The Client.new controller is the following:
#clients_controller
def create
#create new client
if save
redirect_to to_a_path, :notice => "Client created successfull!"
else
flash[:error] = "Error!"
render :action => "new"
end
end
The solutions that I think can be followed:
1. render a partial like the example above, but I don't know how to "stay" in the modal when errors accours (how can I stay in the modal? -> I have tried with client_validation but seems that doesn't work correctly..)
2. make the modal-body as an <iframe> that loads the new_client_path
3. ...
Which one is the best?
After some tricks I have found a working solution:
The view of the modal controller:
<div id="client_modal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="client_modal_label" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="client_modal_label">Create new client</h3>
</div>
<div class="modal-body">
<%= simple_form_for Client.new, html: {"data-type" => :json}, remote: true do |f| %>
<div id="error_explanation" style="display:none;">
</div>
<div class="form-inputs">
# the inputs
# ... and "closing" the modal
The client_controller.create:
def create
# save the data
if #client.save
respond_to do |format|
format.html { redirect_to anagrafe_index_path, :notice => "Client create!"}
format.json { render json: #client, status: :created, location: #client }
end
else
respond_to do |format|
format.html { render :action => 'new'}
format.json { render json: #client.errors.full_messages, status: :unprocessable_entity }
end
end
end
The js.coffee where the modal is raised:
$ ()->
$("form.new_client").on "ajax:success", (event, data, status, xhr) ->
$("form.new_client")[0].reset()
$('#client_modal').modal('hide')
# refreshing the select
$('#error_explanation').hide()
$("form.new_client").on "ajax:error", (event, xhr, status, error) ->
errors = jQuery.parseJSON(xhr.responseText)
errorcount = errors.length
$('#error_explanation').empty()
if errorcount > 1
$('#error_explanation').append('<div class="alert alert-error">The form has ' + errorcount + ' errors.</div>')
else
$('#error_explanation').append('<div class="alert alert-error">The form has 1 error.</div>')
$('#error_explanation').append('<ul>')
for e in errors
$('#error_explanation').append('<li>' + e + '</li>')
$('#error_explanation').append('</ul>')
$('#error_explanation').show()

Rails 3 Partial Will Not Render Via js.erb

I'm having a problem where I try to render a partial through a js.erb after I obtain some data from my controller. I've tried a number of different things, I just can't get the partial to render. The log file shows the partial rendering with a 200 OK message, but nothing happens on the page. This post is similar to the problem I am having:
Rails 3 - render partial js.erb
I have tried to follow the guidance this post, but I'm still having trouble.
Here is my partial with the form __left_date_filter.html.erb =>
<%= form_tag({:controller => 'events', :action => 'dateFilter'}, :class => 'date_form', :remote => true) do %>
<%= datepicker_input "event", :start_date, :class => 'dateFilter', :dateFormat => 'mm/dd/y' %>
<%= datepicker_input "event", :end_date, :class => 'dateFilter', :dateFormat => 'mm/dd/y' %>
<%= submit_tag "Submit" %>
<% end %>
Here is the generated HTML =>
<form accept-charset="UTF-8" action="/events/dateFilter" class="date_form" data-remote="true" method="post">
<div style="margin:0;padding:0;display:inline">
<input name="utf8" type="hidden" value="✓" />
<input name="authenticity_token" type="hidden" value="x4cbSoYnUu2+W6qvtPnKXvXR8Tp3Yh7BP9W0RMyR02g=" /></div>
<input class="dateFilter" id="event_start_date" name="event[start_date]" size="30" type="text" /><script type="text/javascript">
//<![CDATA[
jQuery(document).ready(function(){jQuery('#event_start_date').datepicker({"dateFormat":"mm/dd/y"})});
//]]>
</script>
<input class="dateFilter" id="event_end_date" name="event[end_date]" size="30" type="text" /><script type="text/javascript">
//<![CDATA[
jQuery(document).ready(function(){jQuery('#event_end_date').datepicker({"dateFormat":"mm/dd/y"})});
//]]>
</script>
<input name="commit" type="submit" value="Submit" />
Here is the dateFilter.js.erb =>
$('#content').html("<%= escape_javascript(render(:partial => 'dateFilter')) %>");
Here is the events_controller =>
def dateFilter
eventIn = params[:event]
start_date = Date.parse(eventIn[:start_date])
end_date = Date.parse(eventIn[:end_date])
sql = *redacted*
#events = Event.find_by_sql(sql)
respond_to do |format|
format.html
format.json
format.js
end
end
Here is the application.js =>
$(document).ready(function() {
$('#date_form').submit(function (){
$.ajax({
type: 'POST',
url: "/events/dateFilter",
beforeSend: function (xhr) {xhr.setRequestHeader("Accept", "text/javascript");},
data: { 'start_date' : $("input[name='event[start_date]']").datepicker(), 'end_date' : $("input[name='event[end_date]']").datepicker()}
success: function(data) { $('#content').html(response); }
});
});
This is log data from the server =>
Started POST "/events/dateFilter" for 127.0.0.1 at 2012-12-20 12:18:57 -0500
Processing by EventsController#dateFilter as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"x4cbSoYnUu2+W6qvtPnKXvXR8Tp3Yh7BP9W0RMyR02g=", "event"=>{"start_date"=>"07/01/12", "end_date"=>"07/02/12"}, "commit"=>"Submit"}
**shows SQL Statement getting all records**
Rendered events/_dateFilter.html.erb (89.1ms)
Rendered events/dateFilter.js.erb (90.7ms)
Completed 200 OK in 212ms (Views: 80.5ms | ActiveRecord: 128.2ms)
Then finally, the page I wish to render _dateFilter.html.erb =>
<div class="content">
<table class="table table-striped table-hover">
<thead>
<tr>
<th><%= sortable "event_id" %></th>
<th><%= link_to "Time Created", :sort => "event_date_time_local" %></th>
<th><%= link_to model_class.human_attribute_name(:event_type_id), :sort => "event_type" %></th>
<th><%= link_to model_class.human_attribute_name(:severity_id), :sort => "severity_name" %></th>
<th><%= link_to "Examined", :sort => "event_examined" %></th>
<th><%= link_to model_class.human_attribute_name(:action_required), :sort => "action_required" %></th>
<%#<th><%= model_class.human_attribute_name(:comments) </th>%>
<th><%= link_to model_class.human_attribute_name(:initials), :sort => "initials" %></th>
<th><%= link_to "Ticket ID", :sort => "taskid" %></th>
</tr>
</thead>
</div>
I'm just not sure why it is telling me that it rendered the partial properly, but then nothing happens on my page. I'm not very familiar with JQuery, so there is probably something wrong in my application.js or my datefilter.js.erb files.
A few things:
The ajax call is not necessary if you are using :remote => true in your form_tag. JQuery will handle the call to Rails automatically. You should be able to comment out the code in application.js.
Make sure you have a div that has id="content" in your HTML already.
It's not clear where you are getting a lot of the ruby variables in your _dateFilter.html.erb. Could you start with a simple partial to see if it works, and then you can start adding in details from the #events variable passed from the controller:
.
<div class="content">
<table>
<thead>
<tr>
<th>Test</th>
</tr>
</thead>
</table>
</div>

My form doesn submit with Jquery Validate + Rails Form

I have a form that submits correctly without jquery validate, but does not with jquery validate. Using jquery validate, it correctly shows when the field has less than 6 characters, and the error goes away when it is 6+. However, clicking on the button does nothing. The validate script is:
<% content_for :head do %>
<script type="text/javascript">
$(document).ready(function () {
alert("document ready");
$("#new_hotel").validate({
debug: true,
rules: {
"hotel[name]": {required: true, minlength: 6},
}
});
});
My form is this:
<div class="modal-body">
<%= form_for #hotel do |f| %>
<%= f.label :name %>
<%= f.text_field :name%>
<div class="modal-footer">
<a class="btn" data-dismiss="modal" aria-hidden="true">Cancel</a>
<%= f.submit 'Create Hotel' , :class => 'btn btn-primary', :type => 'submit' %>
</div>
<% end %>

Rails 3 - tinymce doesn't send data

In my app use tinymce editor and the problem is that the form send empty textarea. When I remove Tinymce from this form, so everything's working well.
<%= form_tag({ :controller => 'home', :action => 'process_note' }) do %>
<%= hidden_field_tag 'user_id', #user_note.id%>
<div style="width: 800px;">
<div>Your note:</div>
<div>
<%= text_area_tag 'new_note', #user_note.note, :class => 'mceEditor text', :style => 'width: 700px;height: 250px;' %></td>
</div>
<div>
<%= submit_tag "Save" %>
</div>
</div>
<% end %>
Have anyone a similar experience with this behavior? I have already no idea, where could be a problem