Show ajax based elements after form submit error - ruby-on-rails

I have two select elements in my form, Category and Sub-category. At first, only the category select is shown. When the user makes a selection in the category select, an AJAX request is sent to the server and the subcategory select is shown. It works fine.
Now, when there is some error in the form submit, due to anything, missing some value that is required, or anything, I show the error message, but I cannot retain the same state of the select boxes, I see only the category select, with no value selected, i.e the initial state. Can anyone suggest me how I can preserve the state of these select elements?
Here's a code snippet from my new form:
<div id="category-select">
category <%= collection_select :post_category, :id, #categories, :id, :name,
options = {:prompt => "Select a category"} %>
</div>
<div id="sub-category-select">
</div>
Here's my jQuery script that sends AJAX request when a selection is made on Category select:
$("#post_category_id").change(function() {
var category_id = $('select#post_category_id :selected').val();
if(category_id == "") category_id="0";
$.get('/posts/update_sub_cat/' + category_id, function(data){
$("#sub-category-select").html(data);
})
return false;
});
The AJAX request is made on the update_sub_cat action in the post_controller, which is shown below:
def update_sub_cat
if params[:id].present?
#sub_categories = Category.find_all_by_parent_id(params[:id])
else
#sub_categories = []
end
respond_to do |format|
format.js
end
end
The AJAX request renders update_sub_cat.js.erb file, in which I have used some HMTL
sub-category <%= collection_select :post_sub_category, :id, #sub_categories, :id, :name,
options = {:prompt => "Select a sub-category"} %>
I know, I should not directly use HTML here, but rather use $('sub-category-select).append(...), but I got it working like this, and am planning to change it later.
This is all the code that is involved in this part of my program.
Can anyone help me, please?

I solved the problem, and got the AJAX based element to maintain state. Here's my jQuery code:
$('#before_category_select').loadPage();
jQuery.fn.loadPage = function(){
if($("#new-post-area").length > 0){
$.getJSON('/home/cat_select_state.json', function(data){
$.get('/posts/update_sub_cat/' + data.cat_state, function(data1){
$("#sub-category-select").html(data1);
})
});
}
}
The controller action that I call to get the state of the select elements, which is stored as session variables at the time of page submit:
def cat_select_state
#cat_session = {:cat_state => session[:new_post_category], :sub_cat_state => session[:new_post_sub_category]}
respond_to do |format|
format.json {render :json => #cat_session}
end
end
And finally, I used a default values for the select boxes, which are stored as session variables. If the session variable is null, the default value is the prompt message for the select box.
<%= collection_select :post_category, :id, #categories, :id, :name,
options = {:prompt => "Select a category", :selected => session[:new_post_category]} %>
The HTML for sub-category select element is rendered in the javascript file update_sub_cat.js.erb.
sub-category <%= collection_select :post_sub_category, :id, #sub_categories, :id, :name,
options = {:prompt => "Select a sub-category"} %>
Please suggest if you have any more improvements.

Related

pre-populating form field from database with "second level" association

I have three models: Appointment, Client, and InsuranceProvider
A client has_many :appointments
And a client has_many :insurance_providers (the idea being I"d like to store historical info there).
in my view to create a new appointment, I have this (among other things):
<%= f.association :client, label_method: lambda { |c| "#{c.first_name} #{c.last_name}" }, collection: current_user.clients %>
this is fine, but I'd like to get to the copay field in insurance_providers.
Basically, this is how you'd get there:
appointment.client.insurance_provider.copay
What I'd like to do is pre-populate the "copay amount" field based on the client selected from the dropdown.
How can I do this?
Please let me know if you need to see my models or views explicitly.
If I understand correctly, you want a second select to be populated with values based on the value in the association.
Basically, you need JQuery/AJAX to do this for you. JQuery to watch the first select, and then AJAX to get data from rails based on the value chosen, and JQuery again to add values to the second select.
An alternative would be to use an in-place editor like best_in_place for each select, which would do the AJAX-y stuff for you.
Use ajax to to fetch the values for copay based on the return of the select.
Because there are a lot of steps, I'll lay them out, but you can find them in probably a dozen other SO questions.
Add the Javascript, this coffeescript but it's just your basic on change -> send-data call - so change at will.
#appointment.js.coffee
$(document).ready ->
$(".client_select").on "change", ->
$.ajax
url: "/appointments/new"
type: "GET"
dataType: "script"
data:
client: $(".client_select").val()
Make sure your form has the 2 jquery elements to get data from and push data to.
# First the field to pull from
<%= f.association :client, label_method: lambda { |c| "#{c.first_name} #{c.last_name}" }, collection: current_user.clients, input_html: { class: 'client_select' } %>
# And then the field to push to
<%= f.input :copay_amount, input_html: { class: 'copay_from_client' } %>
This is going to make a request on your "new" action of your appointments controller, so you'll need to add a javascript respond to to make sure it can render the next step, the UJS file.
# appointments_controller.rb
def new
# ... All the stuff you're normally doing and additionally:
#you'll have to adjust the params argument to match your select field
insurance_copay = Client.find(params[:client]).insurance_provider.copay
respond_to do |format|
format.html # new.html.erb
format.js { render "new", locals:{insurance_copay: insurance_copay} }
format.json { render json: #appointment }
end
end
Now add the UJS, new.js.erb
$(".copay_from_client").val('<%= #insurance_copay %>');

Rails Form_For Select With Dual Purpose

I have form for adding a new job. On my form I have a select drop-down list. I need to associate the new job to a customer. The following works great.
<%= f.collection_select :customer_id, Customer.all, :id, :business_name %>
But, what if I want to also be able to send in a customer_id to the new form? Can I have the form's select drop-down show all the possible customers, as above, but have it auto select the customer_id I pass into the form, if a customer_id is passed in?
url = ...jobs/new
OR
url = ...jobs/new?customer_id=5
I apologize if I did not explain this well enough.
Thanks in advance.
--jc
I think you do what you're trying to achieve this by populating the customer_id field on the job you're creating in your controller if customer_id is present in the request params. This should make that particular customer be the initially selected option in the form.
http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select
e.g. Something like.
if params[:customer_id].present?
job.customer_id = params[:customer_id]
end
If you declaring the instance variable #customer in your controller action then you can use selected option as:
<%= f.collection_select :customer_id, Customer.all, :id, :business_name, {:selected => #customer.id} %>

Adding a value-dependent data attribute to a simple_form checkbox collection

I'm generating a list of checkboxes for a single collection like so:
= f.input :parts, as:check_boxes, collection: #parts_list
I want some checkboxes in the collection to disappear/reappear depending on the value of a select widget higher up in the form. (e.g. choosing "Tracker Robot" from the Robot select means that the "Legs" part checkbox disappears and the "Wheels" checkbox appears, etc.)
What I'd like to do is attach a computed data attribute to each individual Part checkbox, with the attribute value listing the Robots that can use that Part; then some JS will do the work of hiding/showing the checkboxes. However, I don't know how I can generate those data attributes using simple_form.
I would normally create a custom "parts" input, but there seems to be a problem with making custom collection inputs; it looks for a named method (collection_parts) inside form_builder.rb, which won't exist, and if I try and extend the FormBuilder it sends me down a major rabbit hole.
I could write some JS to load the data attrs into the generated HTML, but then I have to generate custom JS based on my Rails data, and that feels like the wrong way to do it.
Let's assume that the form is for Order model and you are changing the parts collection based on the value of a field called region.
Update the form view. Specify the id for form, region field and parts field.
= simple_form_for(#order, :html => { :id => "order-form"}) do |f|
= f.input :region, :wrapper_html => { :id => "order-form-region", |
"data-parts-url" => parts_orders_path(:id => #order.id, :region => #order.region)} |
= f.input :parts, as: check_boxes, collection: #parts_list, |
:wrapper_html => { id' => 'parts-check-box-list'} |
Add a new action called parts in the route.rb file.
resources :orders do
collection do
get :parts
end
end
Add the new action to your controller
class OrdersController < ApplicationController
# expects id and region as parameters
def parts
#order = params[:id].present? ? Order.find(params[:id]) : Order.new
#parts_list = Part.where(:region => params[:region])
end
end
Add a helper
def parts_collection(order, parts_list)
"".tap do |pc|
# to generate the markup for collection we need a dummy form
simple_form_for(order) do |f|
pc << f.input(:parts, as: check_boxes, collection: parts_list,
:wrapper_html => {:id => 'parts-check-box-list'})
end
end
end
Add a js view for the action (orders/parts.js.erb)
$('#parts-check-box-list').replaceWith('<%= j(parts_collection(#order, #parts_list)) %>');
Register data change event handlers for region field in your application.js
$(document).ready(function() {
$('#order-form').on("change", "#order-form-region", function () {
// Access the data-parts-url set in the region field to submit JS request
$.getScript($(this).attr('data-parts-url'));
});
});
I think you can do it like this:
= f.input :parts do
= f.collection_check_boxes :parts, #parts_list, :id, :to_s, item_wrapper_tag: :label, item_wrapper_class: :checkbox do |b|
- b.check_box(data: { YOUR DATA ATTRIBUTES HERE }) + b.text
this may be simpler.
Assumptions
#robots - an array containing the list of robots
#parts - a hash containing a list of parts for each robot
Sample Code
# controller
#robots = %w[tracker nontracker]
#parts = { tracker: %w[wheels lcd resistor], nontracker: %w[lcd resistor] }
# view
= f.input :robots, as: :select, collection: #robots, input_html: { id: 'robot-select' }
#parts-list
:javascript
var parts = #{#parts.to_json};
$(document).ready(function() {
$('#robot-select').change(function() {
$('#parts-list').html('');
$(parts[$(this).val()]).each(function(index, text) {
$('#parts-list').append('<input type="checkbox" value=' + text + '>' + text + '</input>')
})
})
})
you can see this working if you clone https://github.com/jvnill/simple_form_search_app and go to /robots
Some input options in SimpleForm accept a lambda that gets called for every item in a collection:
f.input :role_ids, :collection => (1..10).to_a,
:label_method => :to_i, :value_method => :to_i,
:as => :check_boxes, :required=> true,
:disabled => ->(item){ item.even? }
but input_html doesn't seem to be one of them.
The solution is probably to create a custom SimpleForm collection input that applies the data attributes itself. Not as flexible perhaps, but I think this is the only way to go for now.
There's a tutorial page on GitHub that should get you started.

need to add default value in f.select field to existing ones - rails 3.2

With the code I have below in the select field I have all the public_campaigns:
<%= f.select :campaign_id, #public_campaigns.map{|x| [x.name,x.id]} %>
public_campaigns is defined in controller with:
#public_campaigns = #logged_in_user.campaigns.order('created_at desc')
In the form I select the campaign and fill up the rest of the form and at the submit action an invitation is created with campaign_id taken from the campaign I selected in the form, it can be anything from 1 to n
What I need now is to have a default item in select field that will have the value of 0 and named "No campaign", it means I invite someone to a campaign that I have not created yet and in invitation the campaign_id field will be 0.
Thank you for your time.
Do you really need 0? I think use of {:include_blank => "No campaign"} should be enough?
Try this:
<%= f.select :campaign_id, (#public_campaigns.map{|x| [x.name,x.id]} << ["No campaign",0]), {:selected => 0} %>
Well, the fastest way you can do this is something like this:
#public_campaigns = #logged_in_user.campaigns.order('created_at desc')
no_campaign = Campaign.new(:id => '0', :name => 'No Campaign')
#public_campaigns.unshift(no_campaign)
I'm not sure why you are unable to do it this way:
<%= f.collection_select :campaign_id, #public_campaigns, :id, :name, prompt: 'No campaign' %>
Just check if campaign_id.nil? instead of assigning any value to campaign_id

Ruby on Rails and how to render partial using json and jquery

Ruby on Rails newbie whose confused and frustrated :) I've spent over a day on this and think I've probably just confused myself.
Basically, I'm trying to render a partial in a view. Here's what I have specifically:
A form with 2 basic fields: Category and SubCategory. SubCategory changes depending on what the user selected in Category. I'm using "JQuery" with the assets pipeline enabled. This part works:
contact_infos.js.coffee
jQuery(document).ready(->
$("select#contact_info_category_id").change(->
id_value_string = $(#).val()
if id_value_string == ""
# if the id is empty remove all the sub_selection options from being selectable and do not do any ajax
$("select#contact_info_subcategory_id option").remove()
row = "" + "" + ""
$(row).appendTo("select#contact_info_subcategory_id")
else
# Send the request and update sub category dropdown
tmp = '/subcategories/for_categoryid/' + id_value_string + '.json'
$.ajax(
type: 'GET',
dataType: 'json',
url: tmp,
timeout: 2000,
error: (XMLHttpRequest, errorTextStatus, error) -> alert "Failed to submit : " + errorTextStatus + " ;" + error,
success: (data) ->
# Clear all options from sub category select
$("select#contact_info_subcategory_id option").remove()
# put in a empty default line
row = "" + "" + ""
$(row).appendTo("select#contact_info_subcategory_id")
# Fill sub category select
$.each(data, (i, j) ->
row = "" + j.name + ""
$(row).appendTo("select#contact_info_subcategory_id")
)
)
)
)
It generates a json response correctly.
When the form loads, in addition to Category and SubCategory, I also have 2 text fields - previous_value and current_value; however, if
SubCategory == "Full"
then I hide previous_value and current_value and need to insert a partial with new fields.
I'm having no problem hiding previous_value and current_value fields with JQuery works and looks like this (this is inserted into the code above):
$("select#contact_info_subcategory_id").change(->
id_text_string = $("#contact_info_subcategory_id option:selected").text()
if id_text_string == "Full"
$('#contact_info_previous_value_id').hide()
$('#contact_info_current_value_id').hide()
else
$('#contact_info_previous_value_id').show()
$('#contact_info_current_value_id').show()
)
I created a div called "test" in my form where I want to insert the new fields if SubCategory is "Full" and of course, inserting this line into the contact_infos.js.coffee doesn't work:
$('#test').html('<%= escape_javascript render("contact_infos/_full_name_info") %>')
as all I get on the page is the string "<%= escape_javascript render("contact_infos/_full_name_info") %>"
I've tried the following but can't get any to work:
1. creating a new.json.erb file with the following code:
<% self.formats = ["html"] %>
test = {
"html":"<%= raw escape_javascript(render :partial => 'contact_infos/full_name_info',
:content_type => 'text/html')}
%>"
}
This json file never triggered. My controller has this line:
format.json { render json: #contact_info }
Is this the best way to do this? If yes, what can I try next?
2. I saw a posting yesterday (I can't find it now - was on another computer) about creating a javascript variable (I called it fullnamefield) in the application.html.erb layout file as well as adding the js variable to the new.html.erb view, which I did. I also added this line to the contacts_infos.js.coffee:
('#test').html(fullnamefield)
and it worked!! EXCEPT that then when I went to any other area of the site, I got an error.
3. As a workaround, I thought about trying to change the json that my jquery produces to a js and then trying to trigger the new.js.erb. I ran into trouble trying to convert the ajax call. I could create "json" and also "text" dataTypes but not script (not sure why).
So... any ideas/help? I've really been searching and I'm frustrated enough that I'm considering just creating all the fields and hidings/showing them as needed from JQuery, which would be so simple to implement but is just wrong.
UPDATE: Attempt 4 (or is it 40?):
What you wrote got me thinking... I think I'm close but not there yet.
In my _form.html.erb, I added to the Subcategory field data-remote, data-url and data-type:
<div class="field">
<%= f.label :category_id %>
<br/>
<%= collection_select(:contact_info, :category_id, Category.all, :id, :name, options ={:prompt => "--Select a Category--"}) %>
</div>
<div class="field">
<%= f.label :subcategory_id %>
<br/>
<%= collection_select(:contact_info, :subcategory_id, Subcategory.find_all_by_category_id(#contact_info.category_id), :id, :name, options ={:prompt => "--Select a SubCategory"}, "data-remote" => true, "data-url" => "/contact_infos/get_full_fields", "data-type" => :json ) %>
</div>
Then in the contact_infos_controller.rb I added:
def get_full_fields
#full_name = FullName.new
respond_to do |format|
format.js
end
end
In my routes.rb I modified contact_infos by adding collection do...
resources :contact_infos do
collection do
get 'get_full_fields'
end
end
I created contact_infos\get_full_fields.js.erb:
var full_fields_form = $('<%= j(render(:partial => "contact_infos/full_name_info"))%>');
$('#test').html(full_fields_form);
Now when I test this in the browser with debugger and change SubCategory to "Full" I can see that it runs correctly (I think) in that I'm getting this back:
Request URL:http://localhost:3000/contact_infos/get_full_fields?contact_info%5Bsubcategory_id%5D=3
Request Method:GET
Status Code:200 OK
The "Type" is showing up as "text/javascript." The Response tab is just showing the javascript code but nothing is happening/triggering. Even when I place just a
alert('hello');
in the js file nothing happens.
Any ideas why?
Why not do it the same way you get subcategory data? Create a view containing the partial (and corresponding controller action) and call it via ajax when you want to display that content.

Resources