Drop down issue when loading a partial - rails 3 - ruby-on-rails

I am working on rails 3 and using ajax to load a form, there is a country drop down that has values thats not loading properly. Its loading html entities of the "<" and ">" sign like "<" & ">".
This is how i am rendering the partial that has the countries list
$j('#insert_to').append("<%= escape_javascript(render :partial => 'verified_address', :locals => { :item => #item, :original_item => nil, :update_alert => false }).html_safe %>");
The output i am getting is
<span id=\"ship_to_country_container\">\n
<select id
=\"item_ship_to_country\" name=\"item[ship_to_country]\"><option value=\"\">-- Select --<\/option>\n
<option value="" disabled="disabled">-------------</option>\n<option
value="Afghanistan">Afghanistan</option>\n<option value="Aland Islands&quot
;>Aland Islands</option>\n<option value="Albania">Albania</option>\n&lt
;option value="Algeria">Algeria</option>\n<option value="American Samoa&quot
;>American Samoa</option>\n<option value="Andorra">Andorra</option>\n
<option value="Angola">Angola</option>\n<option value="Anguilla"&gt
;Anguilla</option>\n<option value="Antarctica">Antarctica</option>\n<option
value="Antigua And Barbuda">Antigua And Barbuda</option>\n<option value=&quot
;Argentina">Argentina</option>\n<option value="Armenia">Armenia</option
>\n<option value="Aruba">Aruba</option>\n<option value="Australia&quot
;>Australia</option>\n<option value="Austria">Austria</option>\n<option
value="Azerbaijan">Azerbaijan</option>\n<option value="Bahamas">Bahamas
</option>\n<option value="Bahrain">Bahrain</option>\n<option value=&quot
;Bangladesh">Bangladesh</option>\n<option value="Barbados">Barbados&lt
;/option>\n<option value="Belarus">Belarus</option>\n<option value=&quot
;Belgium">Belgium</option>\n<option value="Belize">Belize</option&gt
;\n<option value="Benin">Benin</option>\n<
html entities are getting rendered and not the actual tags
1st call: $j.ajax({
url: "/items/validate_address",
type: 'POST',
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $j('meta[name="csrf-token"]').attr('content'))},
data: data_address,
dataType: 'script'
});
this call the validate_address
<div id="verified_address" style="display:none">
<div id="verified_address_form" style="display:none;">
<%= form_for(item, :remote => true) do |f| %>
<%= render :partial => 'shipments/ship_to_address_form', :locals => {:f => f, :item => item}%>
<input type="hidden" name="update_alert" id="update_alert" value="<%= update_alert %>" />
<p><%= f.submit "Save", :style => 'width: 60px;' %> <%= link_to_function "Cancel", "$('verified_address_view','verified_address_form').invoke('toggle');$('order_address_id').style.position = '';$('order_address_id').style.zIndex = '';" %></p>
<% end %>
</div></div>
3rd Step: shipments/ship_to_address_form has the country dropdwon
<tr>
<td><label for="item_ship_to_country">Country</label></td>
<td>
<span id="ship_to_country_container">
<%= f.country_select :ship_to_country, {},{:selected => item.ship_to_country, :include_blank => '-- Select --'} %>
</span>

I figured out that the issue was the country_select call, i installed the gem country_select and the issue was resolved. Thanks for all your suggestions and help.

Related

Rails Submit button not submitting

I've moved from BS3 to Materialize so I am going through and changing my forms - I have 4 forms that are extremely similar, but as I switched the first one over it's no longer submitting. The button doesn't even seem like it's getting clicked, but I tied a generic 'logMe' function to it and sure enough it is.
My routes are the exact same for both, the new form is
<div class="row">
<%= form_with(model: #statement, local: true) do |form| %>
<% if #statement.errors.any? %>
<% #statement.errors.full_messages.each do |message| %>
<script>
$(function() {
Materialize.toast("<%= message %>", 3000);
});
</script>
<% end %>
<% end %>
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">account_circle</i>
<!--<label for="icon_prefix">SoW Type:</label>-->
<%= form.label :statement_type, 'Type:' %>
<%= form.text_field :statement_type, :id => "disabled", :value => (params[:statement_type]), readonly: true, :disabled => true %>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<i class="material-icons prefix">contacts</i>
<%= form.label :name, "Name:" %>
<%= form.text_field :name, :id => 'required_field1' %>
</div>
<div class="input-field col s6">
<i class="material-icons prefix">contacts</i>
<%= form.label :cost, "Cost:" %>
<%= form.text_field :cost, :id => 'required_field2' %>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<i class="material-icons prefix">date_range</i>
<%= form.label :start_date, "Start Date" %>
<%= form.text_field :start_date, :class => 'datepicker', "data-provide" => 'datepicker', :id => 'required_field4', :placeholder => "YYYY-MM-DD" %>
</div>
<div class="input-field col s6">
<i class="material-icons prefix">date_range</i>
<%= form.label :end_date, "End Date" %>
<%= form.text_field :end_date, :class => 'datepicker', "data-provide" => 'datepicker', :id => 'required_field5', :placeholder => "YYYY-MM-DD" %>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">perm_contact_calendar</i>
<%= form.collection_select(:client_id, current_user.clients.order(:name),:id,:name, :class => "browser-default", :prompt => "Choose a client" ) %>
</div>
</div>
<div class="row">
<div class="col s12">
<%= form.submit 'Submit', :class =>'btn btn-default', :id => 'register', :onclick => "testMe()"%>
</div>
</div>
<% end %>
</div>
<script type="text/javascript">
$(document).ready(function (){
$('select').material_select();
validate();
$('#required_field1, #required_field2').change(validate);
});
function testMe(){
console.log('hi')
}
function validate(){
if ($('#required_field1').val().length > 0 &&
$('#required_field2').val().length > 0
){
$("input[type=submit]").prop("disabled", false);
}
else {
$("input[type=submit]").prop("disabled", true);
}
}
var from_$input = $('#required_field4').pickadate({
selectMonths: true, // Creates a dropdown to control month
selectYears: 15, // Creates a dropdown of 15 years to control year,
today: 'Today',
clear: 'Clear',
close: 'Ok',
closeOnSelect: true,
format: 'yyyy-mm-dd'
}),
from_picker = from_$input.pickadate('picker')
var to_$input = $('#required_field5').pickadate({
selectMonths: true, // Creates a dropdown to control month
selectYears: 15, // Creates a dropdown of 15 years to control year,
clear: 'Clear',
close: 'Ok',
closeOnSelect: true,
format: 'yyyy-mm-dd'
}),
to_picker = to_$input.pickadate('picker')
// Check if there’s a “from” or “to” date to start with.
if ( from_picker.get('value') ) {
to_picker.set('min', from_picker.get('select'))
}
if ( to_picker.get('value') ) {
from_picker.set('max', to_picker.get('select'))
}
// When something is selected, update the “from” and “to” limits.
from_picker.on('set', function(event) {
if ( event.select ) {
to_picker.set('min', from_picker.get('select'))
}
else if ( 'clear' in event ) {
to_picker.set('min', false)
}
})
to_picker.on('set', function(event) {
if ( event.select ) {
from_picker.set('max', to_picker.get('select'))
}
else if ( 'clear' in event ) {
from_picker.set('max', false)
}
})
</script>
I've tried commenting out all JS, switching it to a regular button, linting it and using Rubocop but I don't see anything off. I went through the HTML to make sure the button was inside the form, and it is.
This isn't the first form I've transitioned, but the first I'm having issues with.
(I assume only the view is relevant since it isn't getting to the controller at this point.)
Just to be safe - The view rendering the form is
<div class="row">
<div class="col s12"><span class="flow-text" style="text-align: center;"><h1>New <%= params[:statement_type] %></h1></span></div>
</div>
<% if params[:statement_type] == 'Proposal' %>
<%= render 'proposal_form' %>
<% elsif params[:statement_type] == 'Concept' %>
<%= render 'concept_form' %>
<% elsif params[:statement_type] == 'SoW' %>
<%= render 'sow_form' %>
<% elsif params[:statement_type] == 'Misc' %>
<%= render 'misc_form' %>
<% end %>
<%= link_to 'Back', statements_path %>
SoW + Proposal work. SoW doesn't.
My issue ended up not being HTML based, but Rails based in the end.
My static element that is populated by a param was causing the issue.
<%= f.text_field :statement_type, :id => "disabled", :value => (params[:statement_type]), readonly: true %>
By removing the id: disabled it resolved the inability for the Submit button to submit. Unfortunately, it also makes MaterializeCSS back to highlighting the field when I select it, but my issue was the Submit button not working.

Unable to combine a normal form with Dropzone.js

In My Rails app I need the user to be able to post Facebook-style posts that would always contain text and optionally an image. I need this to happen without a page reload.
Since I'd like to use Dropzone.js to manage the asynchronous image uploads, I've been trying to combine my form with Dropzone without success. I've used mainly this source.
I'm a bit lost here. What I've tried is below. Could you point me into the right direction?
My form here
<%= simple_form_for(#post, remote: true, :authenticity_token => true, html: { multipart: true, class: 'form-inline dropzone', id: 'new_post_form'}) do |f| %>
<div class="dropzone-previews"></div>
<%= f.input :content, :label => false, :placeholder => " Say something here!", as: :text, :required => true, :autofocus => true, :input_html => { id: "new_post_content_field" } %>
<%= f.input :poster_id, :as => :hidden, :required => true, :autofocus => true, input_html: {value: current_user.id } %>
<%= f.input :poster_type, :as => :hidden, :required => true, :autofocus => true, input_html: {value: current_user.class } %>
<%= f.input :community_id, :as => :hidden, :required => true, :autofocus => true, input_html: {value: #community.id } %>
<div class="fallback">
<%= f.input :post_image, :label => false %>
</div>
<%= f.button :submit, input_html: {id: 'submit-all' } %>
<% end %>
The resulting html
<form class="simple_form form-inline dropzone dz-clickable" id="new_post_form" novalidate="novalidate" enctype="multipart/form-data" action="/posts" accept-charset="UTF-8" data-remote="true" method="post"><input name="utf8" type="hidden" value="✓"><input type="hidden" name="authenticity_token" value="3OC6YhVKtCvjXk0QIHQUUG+72PtkkN3NieWvtLmYzitsh2vDvhu2ggPJBcbDII+39CHuFaRqdRHXK27eR6W1Bw==">
<div class="dropzone-previews"></div>
<div class="form-group text required post_content"><textarea class="form-control text required" id="new_post_content_field" autofocus="autofocus" required="required" aria-required="true" placeholder=" Say something here!" name="post[content]"></textarea></div>
<div class="form-group hidden post_poster_id"><input class="form-control hidden" value="2" autofocus="autofocus" required="required" aria-required="true" type="hidden" name="post[poster_id]" id="post_poster_id"></div>
<div class="form-group hidden post_poster_type"><input class="form-control hidden" value="Participant" autofocus="autofocus" required="required" aria-required="true" type="hidden" name="post[poster_type]" id="post_poster_type"></div>
<div class="form-group hidden post_community_id"><input class="form-control hidden" value="1" autofocus="autofocus" required="required" aria-required="true" type="hidden" name="post[community_id]" id="post_community_id"></div>
<input type="submit" name="commit" value="Create Post" input_html="{:id=>"submit-all"}" class="btn btn-default" data-disable-with="Create Post">
<div class="dz-default dz-message"><span>Drop files here to upload</span></div></form>
application.js
Dropzone.options.newPostForm = {
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 100,
maxFiles: 100,
paramName: "post[post_image]",
init: function() {
var myDropzone = this;
$("#submit-all").click(function (e) {
e.preventDefault();
e.stopPropagation();
myDropzone.processQueue();
});
}
}
Create Action in the Posts controller
def create
#post = Post.new(post_params)
respond_to do |format|
if #post.save
#post_comment = Comment.new()
format.js
format.json { render json: { message: "success", fileID: #post.id }, :status => 200 }
else
format.js {render inline: "toastr.error('Something went wrong');"}
format.jsnon { render json: { error: #post.errors.full_messages.join(',')}, :status => 400 }
end
end
end
Currently, if I hit 'submit' I get the flowing params
<ActionController::Parameters {"utf8"=>"✓", "authenticity_token"=>"3OC6YhVKtCvjXk0QIHQUUG+72PtkkN3NieWvtLmYzitsh2vDvhu2ggPJBcbDII+39CHuFaRqdRHXK27eR6W1Bw==", "post"=>{"content"=>"ddddddd", "poster_id"=>"2", "poster_type"=>"Participant", "community_id"=>"1"}, "commit"=>"Create Post", "controller"=>"posts", "action"=>"create"} permitted: false>
So it seems no params that are related to the image are sent to the controller and I'm not sure how I can solve this.
I ended up finding what was the issue.
The input field for the image (below) shouldn't have been included in the form helper
<%= f.input :post_image, :label => false %>
And I was making a mistake setting the id of the submit button. I was using:
<%= f.button :submit, input_html: {id: 'submit-all' } %>
instead of:
<%= f.button :submit, id: 'submit-all' %>
This prevented the JS to select the appropriate form button.

Form button not responding and badly aligned [Refactoring Ruby on Rails]

I'm working on an assignment for a course I'm doing on refactoring some version of the typo blog. I need to add a new form to a page in order to get some information, the problem is that the submit button is not responding and the form is also badly alligned. http://i.imgur.com/5HKMG0L.png
I don't have a good understanding of front-end, so this app is quite confusing for me but this is the way the page is rendered:
**first view that gets called:**
<% #page_heading = _('New article') %>
<%= render "admin/shared/edit", { :form_type => "article", :form_action => { :action => "new", :id => #article.id , :class => ('autosave')} } %>
**admin/shared/edit:**
<% className = form_action.delete(:class) %>
<%= form_tag(form_action, :id => "#{form_type}_form", :enctype => "multipart/form-data", :class => className) do %>
<%= render :partial => "form" %>
<% end %>
[CODE I ADDED TO CREATE A NEW FORM]
***<h3> Merge Articles </h3>
<div class='clearfix'>
<%= form_tag(categories_path, :class => className) do %>
<%= label :article, :merge_with, 'Article ID' %>
<%= text_field :merge_with , '', {:class => 'span1'}%>
<% end %>
<%= submit_tag 'Merge' %>
</div>***
**_form.html.erb:**
<input type="hidden" name="current_editor" id="current_editor" value="<%= current_user.editor %>" />
<input type="hidden" name="user_textfilter" id="user_textfilter" value="<%= current_user.text_filter_name %>" />
<div id="autosave"></div>
<div id="article_keywords_auto_complete" class="auto_complete"></div>
<%= error_messages_for 'article' %>
<div class='editor-right'>
<div class='well'>
<h4><%= _("Publish settings") %></h4>
<div class='actions'>
<%= link_to_destroy_with_profiles(#article) unless #article.id.nil? or #article.state.to_s.downcase == 'draft' %>
<span id='destroy_link'><%= link_to_destroy_draft #article %></span>
<span id='preview_link'><%= link_to(_("Preview"), {:controller => '/articles', :action => 'preview', :id => #article.id}, {:target => 'new', :class => 'btn info'}) if #article.id %></span>
</div>
<div class='clearfix'>
<%= _("Status:") %> <strong><%= #article.state.to_s.downcase %></strong> Change
<ul class='inputs-list'>
<li id='status' style='display: none;'>
<label for="article_published">
<%= check_box 'article', 'published' %>
<%= _("Published") %>
</label>
</li>
</ul>
</div>
<div class='clearfix'>
Comments are <strong>enabled</strong> and trackbacks are <strong>disabled</strong> Change
<ul class='inputs-list' id='conversation' style='display: none'>
<li>
<label for="article_allow_pings">
<%= check_box 'article', 'allow_pings' %>
<%= _("Allow trackbacks") %>
</label>
</li>
<li>
<label for="article_allow_comments">
<%= check_box 'article', 'allow_comments' %>
<%= _("Allow comments") %>
</label>
</li>
</ul>
</div>
<div class='clearfix'>
<%= _("Publish <strong>now</strong>") %> Change
<ul class='inputs-list'>
<li id='publish' style='display: none;'>
<%= calendar_date_select 'article', 'published_at', {:class => 'span3'} %>
</li>
</ul>
</div>
<div class='clearfix'>
<%= _("Visibility:") %> <strong>public</strong> Change
<ul class='inputs-list' id='visibility' style='display: none'>
<li>
<label for="article_password"><%= _("Password:") %>
<%= password_field :article, :password, :class => 'span3' %>
</label>
</li>
</ul>
</div>
<div class='clearfix'>
<%= _("Permalink:") %> Change
<ul class='inputs-list' id='permalink' style='display: none'>
<li>
<%= text_field 'article', 'permalink', {:class => 'span4'} %>
</li>
</ul>
</div>
<div class='clearfix'>
<%= _("Article filter") %>: <strong><%= #article.text_filter.description %></strong> Change
<ul id='text_filter' class='inputs-list' style='display: none'>
<li>
<select name="article[text_filter]" id="text_filter">
<%= options_for_select text_filter_options, #article.text_filter %>
</select>
</li>
</ul>
</div>
<div class='actions'>
<input id='save_draft' type="submit" value="<%= _('Save as draft') %>" name="article[draft]" class='btn info' />
<%= save( _("Publish")) %>
</div>
</div>
<div class='well'>
<h4><%= _("Categories") %></h4>
<%= render 'categories' %>
</div>
<%= get_post_types %>
</div>
<div class='editor-left'>
<div>
<div>
<%= text_field 'article', 'title', :class => 'span1', :style => ' width: 99%', :placeholder => _('Title') %>
</div>
<%= render('images', { :images => #images}) unless #images.empty? %>
<div id='editor-menu'>
<ul class="tabs">
<li id="f" class='<%= "active" if current_user.editor == 'visual' %>'>
<%= build_editor_link("Visual", 'insert_editor', 'fck', 'visual_editor', 'visual') %>
</li>
<li id="s" class='<%= "active" if current_user.editor == 'simple' %> '>
<%= build_editor_link("HTML", 'insert_editor', 'simple', 'simple_editor', 'simple') %>
</li>
</ul>
</div>
<div id="editor">
<div id='quicktags' style='<%= "display: none;" if current_user.editor == 'visual' %>'>
<script type="text/javascript">edToolbar('article_body_and_extended');</script>
</div>
<div id ='visual_editor' <%= "style='display: none;'" if current_user.editor == 'simple'%> >
<%= ckeditor_textarea('article', 'body_and_extended', {:class => 'large', :height => '300px', :rows => '20'}) if current_user.editor == 'visual' %>
</div>
<div id='simple_editor' class='input_text' <%= "style='display: none;'" if current_user.editor == 'visual'%> >
<%= text_area('article', 'body_and_extended', {:class => 'large', :height => '300px', :rows => '20'}) if current_user.editor == 'simple' %>
<%= render_macros(#macros) if current_user.editor == 'simple' %>
</div>
</div>
<h4><%= _("Tags") %></h4>
<div class='class'>
<%= text_field 'article', 'keywords', {:autocomplete => 'off', :style => 'width: 100%'} %>
</div>
<%= auto_complete_field 'article_keywords', { :url => { :action => "auto_complete_for_article_keywords"}, :tokens => ','}%>
</div>
<div class='separator'>
<h4><%= _("Excerpt") %></h4>
<div class=''>
<%= text_area 'article', 'excerpt', {:height => '150', :style => 'width: 100%', :rows => '5'} %>
<span class='help-block'><%=_("Excerpts are posts summaries that are shown on your blog homepage only but won’t appear on the post itself") %></span>
</div>
</div>
<div class=''>
<h4><%= _("Uploads") %></h4>
<p class='help-block'>Uploads will be displayed as attachments in your RSS feed, but won't appear in your articles.</p>
<ul id='attachments' class='inputs-list'>
<%= render 'admin/content/attachment', { :attachment_num => 1, :hidden => false } -%>
</ul>
</div>
</div>
</div>
Any help would be really appreciated. Thanks.
You need to use CSS to align your form to the left. The best way to do this is going into app/assets/articles.css (or any of your CSS files) and adding this line:
.left { text-align: left; }
Then go back into your views and assign anything you want to align to the left the "left" class, for example in your form you can wrap the relevant portions in a div to make everything align left:
<div class="left">
<%= form_tag(categories_path, :class => className) do %>
<%= label :article, :merge_with, 'Article ID' %>
<%= text_field :merge_with , '', {:class => 'span1'}%>
<% end %>
<%= submit_tag 'Merge' %>
</div>

Rails - Drop down list with 'other' that allows creation of new model object

I currently have a rather complicated _request_form for creating new Requests in my website. Currently, when creating a request, employees must choose their name from a dropdown menu like so:
<%= f.collection_select :name, Employee.all(:order => 'name'), :name, :name %>
This selects puts the right Employee in the Request. However, on the off chance the employee isn't in database I'd like an other option in the collection_select that spawns two textboxes (for Employee name and email), and upon form submission makes the new Employee.
I assume this requires some sort of fancy Ajax, but my limited Rails knowledge doesn't extend that far!
Edit:
Here's my full view:
<%= javascript_include_tag :defaults, "nested_form" %>
<div class="request_form">
<% if !#request.errors.empty? %>
<div class="alert alert-error">
<ul>
<% #request.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="well">
<%= nested_form_for #request, html: { multipart: true } do |f| %>
<%= f.label :title %><br />
<%= f.text_field :title %><br /><br />
<%= f.label :name, 'Submitted By' %><br />
<%= f.select :name, Employee.sorted_employees_list.map { |value| [ value, value ] }, :id => "employee_box" %><br />
<div id="new_employee_data">
</div>
<%= f.label :description %><br />
<%= f.text_area :description %><br /><br />
<%= f.label :attachment_uploader, 'Attachments' %><%= f.file_field :attachment_uploader, :multiple => true, name: "data_files[attachment_uploader][]" %><br />
<% unless #request.data_files.empty? %>
<%= f.label :attachment_uploader, 'Current Attachments:' %><br />
<% end %>
<%= f.fields_for :data_files do |attachment| %>
<% if !attachment.object.new_record? %>
<%= attachment.label :attachment_uploader, 'Delete: ' + attachment.object.attachment_uploader_url.split("/").last %>
<%= attachment.check_box :_destroy %>
<% end %>
<% end %>
</div>
</div>
<script>
$(document).ready(function(){
$('#employee_box').append("<option>Other</option>");
});
$('#employee_box').change(function() {
if( $('#employee_box').val() === 'other' ) {
$('#new_employee_data').append("<input type='text' id='employee_name' placeholder='Employee Name'> <br/> <br /></input><input type='email' id='employee_email' placeholder='Employee Email'> </input>");
}else {
$('#employee_name').remove();
$('#employee_email').remove();
}
});
</script>
This includes #Kirti's suggestion. However, I can't seem to make it work!
Popup dialog is good choice, I think!
1) Add to your Gemfile, and run bundle:
gem 'jquery-ui-rails'
2) Activate jquery-ui javascript (application.js):
//= require jquery.ui.dialog
3) Link jquery-ui stylesheets (application.css):
*= require jquery.ui.dialog
4) Prepare data for select (employees_controller.rb)
def new
#prices = Price.all.map{|p| [p.price, p.id] }
#prices << ['Create New', 'new_id']
end
5) Display select component on view (employees/new.html.erb):
<%= select_tag :employee, options_for_select(#employees) %>
<div id="new_employee_dialog">
<label for="name" type="text">Employee name:</label>
<input name="name" type="text"/>
<label for="email" type="text">Employee email:</label>
<input name="email" type="email"/>
</div>
6) This javascript work with dialog window and send ajax request (assets/javascripts/employees.js.coffee):
$ ->
$("#new_employee_dialog").dialog
modal: true
width: 400
height: 300
autoOpen: false
draggable: false
dialogClass: "without-header"
buttons: [
text: "Cancel"
click: ->
$(this).dialog "close"
,
text: "Ok"
click: ->
modalForm = $(this)
$.post "/users/form_create",
employee_name: $(modalForm).find("input[name='name']").val()
employee_email: $(modalForm).find("input[name='email']").val()
, (data, status) ->
if data['status'] == 'ok'
modalForm.dialog "close"
alert "Ok"
else
alert "Oops"
]
$('#employee').change ->
selected_employee_id = jQuery("#employee").val()
console.log('selected id: ' + selected_employee_id )
if selected_employee_id == 'new_id'
$("#new_employee_dialog").dialog("open");
7) Create method to catch ajax request on server-side (employees_controller.rb):
def form_create
employee_name = params[:employee_name]
employee_email = params[:employee_email]
# create new user..
respond_to do |format|
format.json { render :json => {status: 'ok'} }
end
end
8) Add it to routes.rb:
post 'users/form_create' => 'users#form_create'
Add an empty div tag(placeholder) where you want to spawn the two input fields:
<div id="new_employee_data">
</div>
Add the following jQuery at the bottom of the view:
<script>
$(document).ready(function(){
$('#request_name').append("<option value='other'>Other</option>");
});
$('#request_name').change(function() {
if( $('#request_name').val() === 'other' ) {
$('#new_employee_data').append("<input type='text' id='employee_name' placeholder='Employee Name'> <br/> <br /></input><input type='email' id='employee_email' placeholder='Employee Email'> </input>");
}else {
$('#employee_name').remove();
$('#employee_email').remove();
}
});
</script>
where,
replace #request_name with the id generated for your collection_select.
You will also need to add code for creating the new employee in the action which is executed at form submission.
NOTE: I am no expert in AJAX but you could adapt the above jQuery and take it from there.

Rails: How do I re-render a partial view on a page?

I have a webpage with a partial view that has a button and displays some information. When the user clicks the button in this partial view, I need to be able to update that partial view from the controller within the action that gets called. Specifically, there is a string that I want to update. Here is my code so far, but it's not working..
partial view (_printLabel.rhtml)
<% if #printAsinEnabled %>
<%= check_box_tag(:needPrint, :needPrint, false,
:onchange => "if (this.checked) $('printLabelAction').show(); else $('printLabelAction').hide();") %>
<%=_('Need to print label?')%><br /><br />
<div id="printLabelAction" class="action" style="display:none;">
<% onPrintLabelClick = generateAjaxRequest(
{:controller => #controller.controller_name,
:action => 'processPrintLabelRequest',
:creturnWipItemId => creturnWipItemId,
:barcode => collectedItemData.fnsku,
:title => asinInfo["title"]},
["parameters: Form.serializeElements([$('printerAddress'),$('printerRemote_true'),$('printerRemote_false')])"]) %>
<%=_('Printing')%>: <%= collectedItemData.fnsku %> <br /> <br />
<%= radio_button_tag(:printerRemote, :false, !session[:printRemote]) %>
<label for="printerRemote_false"><%=_('Local Printer')%></label> <br />
<%= radio_button_tag(:printerRemote, :true, session[:printRemote]) %>
<label for="printerRemote_true"><%=_('Remote Printer')%> - <%=_('Printer Address')%>:</label>
<%= text_field_tag(:printerAddress, session[:printerAddress],
:onchange => onPrintLabelClick,
:onclick => "$('printerRemote_true').checked = true")%> <br />
<div style="text-align:right;">
<%= button_to_function(_("Print Label"), onPrintLabelClick) %>
</div>
<%=_('Error?')%>: <%= errorMessage %> <br /> <br />
</div>
Here is the div where it gets rendered originally:
<div id="Block_asinSummary" class="block">
...
...
<td height="200px" width ="70%">
<%= link_to asinInfo["title"], asinInfo["link"], :target => "_blank" %><br/><br/>
<% if !asinInfo["clothingSize"].nil? %>
<b><%= _('Size')%>:&nbsp</b> <%= asinInfo["clothingSize"]%><br>
<% end %>
<font size='1'>
<% sku = collectedItemData.displaySku %>
<% if sku != collectedItemData.asin%>
<b>SKU:</b> <%= sku %><br>
<% else %>
<b>ASIN:</b> <%= collectedItemData.asin %>
<% end %>
<%= render(:partial => 'printLabel', :locals => { :creturnWipItemId => creturnWipItemId, :collectedItemData => collectedItemData, :asinInfo => asinInfo, :errorMessage => "HI" })%>
</font>
</td>
</tr>
</table>
...
...
<% end %>
And here is the controller code that is supposed to update "errorMessage" with a new string when clicked:
render(:partial => 'printLabel', :layout => false, :locals => { :creturnWipItemId => creturnWipItemId, :collectedItemData => #collectedItemData, :asinInfo => asinInfo, :errorMessage => "Bye" })
I am not seeing any errors from this, but the errorMessage string is not updating from "HI" to "Bye".
You can't call render partial from your controller. Instead, render the template and pass a different error message to the partial using an instance variable.

Resources