Cocoon Callbacks won't work - javascript

I've read through other questions and the cocoon github wiki as well, tried out the sample Rails 4 demo (which works) but I can't get the callbacks to fire on my project.
My gem file is a bit long but the most relevant gems IMHO are cocoon from master (1.2.6), thrubyracer, turbolinks, and spring.
form (note that data-no-turbolinks false and true have had no effect):
%div{"data-no-turbolink" => "false"}
= simple_form_for #course, html: { class: "pure-form"} do |f|
= f.error_notification
.form-inputs
= f.input :name, label: false, placeholder: 'Nombre del Curso', html: {id: 'nombre'}
#subjects.well
= f.input :materia, collection: #materia, prompt: 'Seleccione una materia', value_method: :name
= f.input :tema_de_curso, collection: #tema, prompt: 'Seleccione el tema del curso', value_method: :name
= f.input :grado, collection: #grado, prompt: 'Seleccione el grado', value_method: :name
#bimesters.well
= f.simple_fields_for :bimesters do |bimester|
= render 'bimester_fields', :f => bimester
.links
= link_to_add_association 'Agregar Bimestre', f, :bimesters, class: 'btn btn-primary'
.form-actions
= f.button :submit, class: 'btn btn-success btn-block btn-lg'
partial:
.nested-fields
= f.input :name, collection: #bims, label: 'Bimestre', prompt: 'Seleccione el bimestre', value_method: :name
= link_to_remove_association 'Eliminar Bimestre', f, class: 'btn btn-danger pull-right', style: 'margin-bottom: 1em; '
JS (tried with this extract from the demo project to keep it simple):
$(document).ready(function() {
$('#bimesters').bind('cocoon:before-insert', function(e,task_to_be_added) {
console.log(task_to_be_added);
task_to_be_added.fadeIn('slow');
task_to_be_added.fadeIn('slow');
});
});
Relationship is working correctly as well so models and controller should be fine. I've got the sensation that it might be something to do with turbolinks but all tested permutations have failed.
My main goal is to get the id of the elements that have been created because I'm filtering other nested form partials based on these selections.

Related

Getting Dropzone.JS to work with Carrierwave and multiple images

I'm fairly new to Rails and I've managed to get multiple uploading to work with carrierwave (after about a week). Now I would like to make the uploading process a bit nicer. I'm not sure what's going on but I can't seem to get it working.
My form looks like this:
.edit-container
= simple_form_for #post, html: { multipart: true } do |f|
.edit-form
= f.input :title
= f.input :location, disabled: true
= f.input :price
= f.input :description
= f.input :contact_number, placeholder: "(999) 999-9999"
= f.label "Category"
= f.text_field :category_name, data: {autocomplete_source: Category.order(:name).map(&:name)}, placeholder: "Choose a category"
= f.fields_for :post_attachments do |p|
= p.file_field :image, :multiple => true, name: "post_attachments[image][]"
= f.button :submit
%script
$('#post_location').val("#{request.location.city}, #{request.location.state}")
I've tried doing this:
.edit-container
= simple_form_for #post, html: { multipart: true, class: "dropzone" } do |f|
.edit-form
= f.input :title
= f.input :location, disabled: true
= f.input :price
= f.input :description
= f.input :contact_number, placeholder: "(999) 999-9999"
= f.label "Category"
= f.text_field :category_name, data: {autocomplete_source: Category.order(:name).map(&:name)}, placeholder: "Choose a category"
= f.fields_for :post_attachments do |p|
= p.file_field :image, :multiple => true, name: "post_attachments[image][]"
= f.button :submit
%script
$('#post_location').val("#{request.location.city}, #{request.location.state}")
And this is the result (obviously NOT what I want):
The error message says:
ActionController::UnknownFormat in PostsController#create ActionController::UnknownFormat
Could you walk me through implementing dropzone.js to my application?

To Ruby on Rails - authenticity_token does not work

I'm a beginner programmer on Ruby on Rails.
I have a form that adds an object with attached. The file is stored on the cloud from Amazon S3.
Form done through javascript using ujs. In the form of added parameter: remote: true. But saving does not occur, and there is an error:
Missing template cards/create, application/create with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :coffee, :slim]}.
Help what to do?
my form:
= simple_form_for [#deck, #card], remote: true, authenticity_token: true do |f|
p
= f.input :original_text, as: :string, label: 'Original text', input_html: { class: 'form-control' }
p
= f.input :translated_text, as: :string, label: 'Translated text', input_html: { class: 'form-control' }
p
= f.file_field :picture
p
= f.button :submit, data: { disable_with: 'Сохраняется...' }, class: "btn btn-success btn-lg btn-block", id: "btn-login"
my new.js.erb:
$("#modal-window").html("<%= j render 'cards/new' %>");
my create.js.erb:
$("#modal-window").modal("hide");
$(".cards-index").html('<%= j render 'cards/all', cards: #cards %>');
$("#card_title").val('');
Great! Problem solved.
Added gem 'remotipart'
2 Added to the file application.js after //= require jquery_ujs string //= require jquery.remotipart
3 Added to the form string authenticity_token: true

How to make a input field visible when a button is clicked or create the same field when a button is clicked for ruby on rails

rails newbie here.
this is my current form
<%= f.input :campaign_name , :input_html => {:style=> 'width: 300px'} %>
<%= f.input :date_range, :input_html => {:style=> 'width: 300px'}%>
<%= f.label :first_event %>
<%= f.collection_select :first_event, eventNames, :to_s, :to_s, include_blank: true %>
<br><br><br>
<%= f.label :second_event %>
<%= f.collection_select :second_event, eventNames, :to_s, :to_s, include_blank: true%>
what i want is this, when user clicks "add filter" i want another field to pop up with the same eventNames array as a collection select.I tried to create another button and get it's tag and if its not the submit button and its add filter button render another form.
but this is terribly bad as a interface and as a user experience.
i want my user to be able to remove the second event field at anytime, without having to submit the form.
So i need to add another button in it to remove the newly made visible form.
How can i achieve this
As i said in my comment if you have a restriction that a user could add only a single or lets say a fixed number of filters then you can simply show and hide your collection by js. Your form would have a hidden collection list
<%= f.input :campaign_name , :input_html => {:style=> 'width: 300px'} %>
<%= f.input :date_range, :input_html => {:style=> 'width: 300px'}%>
<%= f.label :first_event %>
<%= f.collection_select :first_event, eventNames, :to_s, :to_s, include_blank: true %>
<br><br><br>
<%= f.label :second_event %>
<%= f.collection_select :second_event, eventNames, :to_s, :to_s, include_blank: true%>
<%= f.label :third_event, class: "hidden" %>
<%= f.collection_select :third_event, eventNames, :to_s, :to_s, include_blank: true, class: "hidden"%>
hide your collection by css
.hidden{display: none;}
and show it by js when a user click on add filter, assuming it's a link you could do:
= link_to "Add Filter", "#", id: "add-filter"
$(document).on("click","#add-filter", function(e){
$(".hidden").show();
e.preventDefault();
});
If user can add multiple filters then you'll need to add them by ajax. For ajax follow these steps:
a. Create a custom route for your action:
post "/filter" => "your_controller#add_filter", as: "filter"
b. create your link for adding filter:
<%= link_to "Add Filter", filter_path, id: "add-filter", data: {event_id: "2", url: filter_path}%>
c. Get event_id by js and send a ajax request:
$(document).on("click","#add-filter".function(e){
var eventId = $(this).data("eventId");
var url = $(this).data("url");
$.ajax({
type: "POST",
url: url,
data: {id: eventId}
});
})
d. Create add_filter action in your controller:
def add_filter
#event_id = params[:id]
respond_to do |format|
format.js
end
end
e. Create your new collection and append it by js in app/views/your_controller/add_filter.js.erb file
var label = "<%=j label_tag "#{#event_id.humanize}_event" %>"
var collection = "<%=j collection_select(:resource, "#{#event_id.humanize}_event".to_sym , eventNames, :to_s, :to_s, include_blank: true) %>"
$("#form_id").find("select").last().after(label).after(collection);
$("#add-filter").data("eventId","<%=j #event_id + 1 %>");
You'll have to use humanize or number_and_words to convert your #event_id to words format and also you'll have to change :resource accordingly

Rails 4 datetimepicker and cocoon gem

Hi have problem with cocoon: https://github.com/nathanvda/cocoon and datetimepicker:http://xdsoft.net/jqplugins/datetimepicker/. When I add through cocoon new nested field my calendar not showing up. I think that I must user cocoon after:insert event in my javascript file but I tried every way and this is not working.
This is my views:
costs.html.haml
= simple_form_for [:partners, #car], url: wizard_path do |f|
= f.simple_fields_for :costs do |cost|
= render 'cost_fields', f: cost
#links
= link_to_add_association '+', f, :costs
= link_to t('cars.back'), previous_wizard_path
= f.submit t('cars.next'), class: 'btn btn-primary'
and my cost_fields partial:
.nested-fields
%table.table.table-striped.table-bordered.dupa
%thead
%th.field
= f.association :cost_type
%th.field
= f.input :netto_price
%th.field
= f.input :document_number
%th.field
= f.association :vat
%th.field
= f.input :type_of_cost
%th.field
= f.input :date, as: :string , :input_html => { :class => 'date' }
= link_to_remove_association "X", f
Any ideas?
As this post eludes, this is because the dynamically added elements are not yet in the DOM.
Try to add a class or id before your nested simple fields (this will already be in the DOM), e.g.:
#container
= f.simple_fields_for :costs do |cost|
= render 'cost_fields', f: cost
Then in your javascript file:
$(document).on('ready page:change', function() {
$('#container').on('cocoon:after-insert', function() {
$('.datetimepicker').datetimepicker();
})
})
Also, I've used this datepicker gem, which allows you to generate a wrapper input/custom date/time fields
= f.input :date, :as => :date_picker

jQuery Tokeninput Error in Rails

I'm trying to use jQuery Tokeninput as shown in Railscast #258 (revised). When I enter something in the tokeninput field, the field does not dropdown with results and I get the following javascript error: Uncaught TypeError: Cannot call method 'replace' of undefined.
My json data works fine when I do a manual query on it, and the server request looks fine. I am trying to search the content column in my issues table, so I set propertyToSearch to "content".
Here is my code:
coffeescript:
jQuery ->
$('#fact_issue_tokens').tokenInput "/issues.json"
theme: 'facebook'
zindex: 11001
propertyToSearch: 'content'
tokenValue: 'content'
hintText: 'Enter an issue'
preventDuplicates: true
Issue Model:
def self.tokens(query)
issues = where("content like ?", "%#{query}%")
if issues.empty?
[{id: "<<<#{query}>>>", content: "New: \"#{query}\""}]
else
issues
end
end
def self.ids_from_tokens(tokens)
tokens.gsub!(/<<<(.+?)>>>/) { create!(content: $1).id }
tokens.split(',')
end
Issues Controller:
def index
#issues = Issue.order(:content)
respond_to do |format|
format.html
format.json { render json: #issues.tokens(params[:q]) }
end
end
Form:
<%= form_for(Fact.new, :url => kase_facts_path(current_kase), :html => {:class => "form-
inline"}) do |f| %>
<%= f.text_field :page, placeholder: 'Page' %>
<%= f.text_field :description, placeholder: 'Description' %>
<%= f.label :issue_tokens, 'Issue tags' %>
<%= f.text_field :issue_tokens %>
<%= f.hidden_field :source_id, :value => #source.id %>
<%= f.submit 'Add Fact' %>
<% end %>
#Scott you try this
jQuery ->
$('#fact_issue_tokens').tokenInput '/issues.json'
theme: 'facebook'
tokenLimit: 5
minChars: 4
preventDuplicates: true
searchingText: "Enter an issue..."
prePopulate: $('#fact_issue_tokens').data('load')
and think on your index because you are using (:content) not name might be your problem. I am bot sure why but i used title and i had a problem, i thought it was mysql or something.
When you visit
http://localhost:3000/issues.json
Do you get the JSON data?
Edit.
Can you please try this for your form?
<div class="field">
<%= f.label :issue_tokens, "Issues" %><br />
<%= f.text_field :issue_tokens, data: {load: #fact.issues} %>
</div>

Categories

Resources