text field with dropdown in rails - javascript

I'm trying to build a form field that can either accept a text entry, or select an option from a dropdown. In rails, the autocomplete plugin is close to what I need, except I want the dropdown to be available before the user types anything in the text field. Is there an example of this out there somewhere?
thx for the help,
-C

I have used this code on a view to select a date or enter a name (I hope you read HAML):
%center
- form_remote_tag :update => 'filter_counts', :url => { :action => 'name_filter', :controller => 'dictated_exams', :method => :post } do
Please enter part of a name ('%' is the wildcard character):
= text_field_tag 'search', nil, :maxlength => 15, :size => 15
= submit_tag 'Search'
%b OR
pick the exam date:
= calendar_date_select_tag "date", Date.today, :time => false, :valid_date_check => "date < (new Date()).stripTime()"
= image_tag "spinner.gif", :align => "absmiddle", :border => 0, :id => "spinner", :style => "display: none;"
= observe_field :date, :with => :date, :frequency => 1, :url => {:action => 'filter_widget', :controller => 'dictated_exams', :method => :post }, :update => :filter_counts, :before => "Element.show('spinner')", :success => "Element.hide('spinner')"
On the other hand, maybe you're just looking for this:
Rails' observe_form method
Basically, the question is : do you need to have those two methods of entry in a single form, or can they be separate? If so, you can also watch them separately.

Related

Ruby on Rails 3 Partial Pages

For a certain employee I have a report. Each report has some shifts. Each shift can be corrected. I am migrating from Ruby 2 to Ruby 3. I am working with partial pages. When I click on Correct, a partial page appears, when I click on Update, page should go back to the partial page Details with the ID of that employee.
_modify_item.html.erb:
<%= form_for :modified_item, :url => {:action => :modify_item, :report_id => #monthly_report.id, :modified_item_id => #modified_item.id,remote: true} do |form| %>
<table width=100% height=100%>
<td width=150 style='border: 0px; background-color: #eee' align=center>
<%= form.hidden_field :report_id, :value => #monthly_report.id %>
<%= submit_tag 'Update', :name => 'update', :value => 'Update', :class => 'highlighted_button' %>
<%= link_to 'Cancel',
{:action => 'details', :report_id => #monthly_report.id},
:class => 'highlighted_button',
remote: true %>
</td>
</tr>
</table>
<% end %>
controller.rb:
def modify_item
#modified_item = Employee::MonthlyReportItem.find(params[:modified_item_id])
#monthly_report = #modified_item.report
begin
#modified_item.update_attributes!(params[:modified_item])
flash[:notice] = 'Position was updated.'
flash[:warning]=#modified_item.verification_problems if !#modified_item.correct?
redirect_to('/accounts/salary/details', :report_id => #monthly_report.id) and return
rescue Exception => e
flash.now[:error] = "Some of the values are missing or are incorrect. Try again."
end
#render(:partial => 'details') and return
end
modify_item.js.erb: (tried didn't succeed)
//$("#salary_popup").html("<%= j(render partial: 'details') %>");
Update: Forgot to mention the exact error which points inside of the if
Couldn't find Employee::MonthlyReport without an ID
Rails goes into details function and tries this:
def details
if params[:item].nil?
#monthly_report = Employee::MonthlyReport.find(params[:report_id])
else
#monthly_report = Employee::MonthlyReport.find(params[:item][:report_id])
end
..
end
Does the hidden field you create have the name attribute? If not trying adding that.

How to add Javascript to simple_form?

I'm using simple_form with Rails 3.2.5. I have a form that looks like this:
<%= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => {:class => 'form-vertical' }, :html => {:name => "new_user"}) do |f| %>
<%= f.error_notification %>
<%= f.input :field_one,
:placeholder => '30000',
:autofocus => true,
:required => true,
:html => {:onFocus => 'startCalc();'},
:html => {:onBlur => 'stopCalc();'} %>
# More form fields
<% end %>
I'm trying to call a Javascript driven calculation when a user enters a number in the form field, but the Javascript isn't showing up in the outputted HMTL:
<input autofocus="autofocus" class="numeric decimal required" id="field_one" name="user[field_one]" placeholder="30000" step="any" type="number" />
Does anyone know how to get simple_form to add these bits of Javascript?
Thanks!
Greg
I see my error now. As per the simple_form documentation, I need to use:
:input_html => {:onFocus => 'startCalc();'},
:input_html => {:onBlur => 'stopCalc();'}
This works!

fields_for with mongoid embeds_many nested documents

attempting to use this railscast as a guide:
http://railscasts.com/episodes/197-nested-model-form-part-2?view=asciicast
and running into this error:
`#search[queries_attributes][new_queries][queries' is not allowed as an instance variable name
models:
#search.rb
class Search
include Mongoid::Document
include Mongoid::Timestamps
belongs_to :user
field :name, :type => String
embeds_many :queries
accepts_nested_attributes_for :queries, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
#query.rb
class Query
include Mongoid::Document
field :columns, :type => String
field :types, :type => String
field :keywords, :type => String
embedded_in :search, :inverse_of => :queries
end
searches controller :
def new
#search = Search.new
#search.queries.build
#3.times { #search.queries.build }
end
_form.html.haml partial:
= form_for(#search) do |f|
= f.label 'Name this search'
= f.text_field :name, :class => 'text_field'
= render :partial => 'query', :collection => #search.queries, :locals => { :f => f }
= link_to_add_fields "Add Query", f, :queries
.actions
= f.submit
_query.html.haml partial:
.fields
= f.fields_for "queries[]", query do |q|
= q.label 'Search Datatype'
= q.select :types, Query::TYPES
= q.label 'In Column'
= q.select :columns, #search.record_columns
= q.label 'For Keywords:'
= q.text_field :keywords, :class => 'text_field'
= q.hidden_field :_destroy
= link_to_function "remove", "remove_fields(this)"
searches helper:
module SearchesHelper
def link_to_add_fields(name, f, association)
new_object = f.object.class.reflect_on_association(association).klass.new
fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
render(association.to_s.singularize , :f => builder)
end
link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")"))
end
end
javascript:
function remove_fields(link) {
$(link).prev("input[type=hidden]").val("1");
$(link).closest(".fields").hide();
}
function add_fields(link, association, content) {
var new_id = new Date().getTime();
var regexp = new RegExp("new_" + association, "g");
$(link).parent().before(content.replace(regexp, new_id));
}
when the line:
= link_to_add_fields "Add Query", f, :queries
is commented out, it works as expected, but I need to be able to add additional queries
via this helper.
for testing multi queries I am triggering the creation in the controller 3.times
also in the error message the last "]" is stripped off.. not sure what I am missing
sorry for all the tags, but not sure where the issue lies
looks like this was the fix:
= f.fields_for :queries, query do |q|
Two thoughts:
I would name the Query class something else, it probably conflicts with some stuff inside mongoid as per the error message you specified:
#search[queries_attributes][new_queries][queries' is not allowed as an instance variable name]
Also googling your problem I came across this:
http://www.jtanium.com/2009/11/03/rails-fields_for-is-not-allowed-as-an-instance-variable-name/
Something must be nil where it shouldn't be.

How to pass a variable to render?

This is the line in my new.js.erb that calls the render function
$('.node_container').append("<%= escape_javascript(render(#care_point, :locals => {:care_map => #care_map}))%>");
Gives error message:
ActionView::Template::Error (undefined local variable or method `care_map'
for my partial _care_point.html.erb:
<%= link_to 'Delete', [care_map, care_point], :confirm => "Are you sure?", :method => :delete, :remote => true, :class => 'delete' %>
To pass locals variables, you must use
render :partial => partial_name, :locals => { # all your vars here }
and not the mere:
render #var
See doc here, para 3.4.4.

Ruby variable in :with of observe_field

I need to send a class name with my observe_field call so I can update the correct text_field (there are multiples on the same page)
<%= observe_field "songlists_" + section.id.to_s + "_song_name",
:frequency => 0.5, :url => { :controller => :songlists, :action =>
:get_artist }, :update => text_class ,
:with => "'song_name=' +encodeURIComponent(value)+'&songlists_classname='+ xxxxxxxx" %>
Is there a way of inserting a ruby variable into the :with statement where 'xxxxxxxx' is displayed above?
Or any other way?
Sure, why not? You're just passing a string to :with, so insert a variable into like you would any other string, e.g. "...&songlists_classname=#{your_variable}":
<%= observe_field "songlists_#{section.id}_song_name",
:frequency => 0.5,
:url => { :controller => :songlists, :action => :get_artist },
:update => text_class,
:with => "'song_name=' + encodeURIComponent(value) + '&songlists_classname=#{your_variable}'" %>

Categories