How to check that all target values have changed in StimulusJS? - javascript

I have an index page where I have to filter Invoices by due_date to prepare them for mass edition. The idea is to keep the submit button disabled until a start_date and end_date have been selected.
I have the following simple_form working with flatpickrJS and I have added data-targets to it's input fields:
<div class="col-md-6 my-2">
<%= simple_form_for :date_params, { url: admin_invoices_batch_edit_index_path, method: :get } do |f| %>
<%= f.input :start_date, as: :string, placeholder: "Start date for filter",
input_html: { data:{ controller: "flatpickr", target: "required",
attributes:{ enableTime: false, enableSeconds: false } } }
%>
<%= f.input :end_date, as: :string, placeholder: "End date for filter", input_html: { data:{ controller: "flatpickr", target: "required",
attributes:{ enableTime: false, enableSeconds: false } }
}
%>
<%= f.button :submit, "Filtrar por fecha" %>
<% end %>
</div>
I also have this other simple_form to select a due_date to which all Invoices will be updated, and I need to keep this form's submit button disabled until all required targets have been selected (that is until a start and end date has been selected in the first form).
<div class="col-md-6 my-2" data-controller="activable">
<%= simple_form_for :due_date, { url: admin_invoices_batch_edit_index_path } do |f| %>
<%= f.input :due_date, as: :string, placeholder: "Nueva fecha de recibo",
input_html: { data:{ controller: "flatpickr",
attributes:{ enableTime: false, enableSeconds: false } } }
%>
<% if params[:date_params].present? %>
<%= hidden_field_tag :start_date, params[:date_params][:start_date] %>
<%= hidden_field_tag :end_date, params[:date_params][:end_date] %>
<% end %>
<%= f.button :submit, "Update Invoices", id: "deactivable-submit", disabled: true %>
<% end %>
</div>
This is my Stimulus controller but I don't know how to check that all requiredTargets have been selected so the disabled button gets enabled.
import { Controller } from 'stimulus';
export default class extends Controller {
static targets = ['deactivable required']
initialize() {
}
connect() {
this.requiredTargets.forEach((element) => {
element.config.onChange.push(function() { } ); })
// check that all required targets have been selected?
}
toggle(){
this.deactivableTargets.toggleAttribute("disabled");
}
}

Related

Wrong image url is passed for one form and correct to another form from partial in Rails 4

I am using a partial that is rendered in two forms belonging to two different controllers as below:
update_user.html.erb
<%= form_with model: #user,
url: {
controller: :profile,
action: :update_user
},
method: :post,
local: true do |f| %>
<%= render partial: 'shared/user_registration_fields', locals: { f: f, profile: #profile } %>
<%= f.submit 'Confirm' %>
<% end %>
new_user.html.erb
<%= form_for #user,
url: {
action: :register_user
},
method: :post,
local: true do |f| %>
<%= render partial: 'shared/user_registration_fields', locals: { f: f, profile: #profile } %>
<%= f.submit 'Confirm' %>
<% end %>
One field in partial is as below:
partial.html.erb
<%= f.fields_for :profile, profile do |prform| %>
<%= prform.label :date_of_birth, 'DOB' %><br />
<%= prform.text_field :date_of_birth, { class: 'datepicker', title: "Date_of_birth", value: (f.object.date_of_birth.strftime("%d-%m-%Y") if f.object.date_of_birth.present?) } %>
The image is rendered using jquery as below:
$( ".datepicker" ).datepicker({
showOn: "button",
buttonImage: "assets/form_images/calendar.png",
buttonImageOnly: true,
buttonText: "Select date of birth",
dateFormat: 'dd-mm-yy',
});
The first form is in the following path -> app/views/profile/update_user.html.erb
The second form is in the following path -> app/views/login/new_user.html.erb
The partial is in the following path -> app/views/shared/_partial.html.erb
Now the image assets/form_images/calendar.png is being shown in this file new_user.html.erb but not in this update_user.html.erb. When I checked the image url from browser, for new_user.html.erb it is assets/form_images/calendar.png which is correct but for update_user.html.erb it is profile/assets/form_images/calendar.png which is wrong. Why is it showing like this? What am I doing wrong here?
That is because, you are using profile nested attributes and rails is appending profile path. Rename your JS file by appending .erb like filename.js.erb and replace buttonImage code like below and try.
buttonImage: "<%= asset_path('form_images/calendar.png') %>";

I want to update my user list on submitting the club form which automatically creates a club admin which in turn is a user in activeadmin

My dashboard.rb is:
ActiveAdmin.register_page "Dashboard" do
menu priority: 1, label: proc{ I18n.t("active_admin.dashboard") }
content title: proc{ I18n.t("active_admin.dashboard") } do
# form render 'form'
# Here is an example of a simple dashboard with columns and panels.
columns do
column class: "users" do
table_for User.all.order(:created_at), input_html: { class: "table table-bordered" } do
column "User Id", :id
column "Email", :email
column "User Role" do |role|
role.profile.role
end
end
end
column do
render partial: 'form', locals: { club: Club.new }
end
end
end
end
My form partial is in app/views/admin/dashboard/_form.html.erb and it is:
<%= semantic_form_for :club, url: admin_clubs_url, method: :post, builder: ActiveAdmin::FormBuilder, remote: true do |club| %>
<%= club.inputs "Details" do %>
<%= club.input :name, label: 'Club Name' %>
<%= club.input :email, label: 'Club Admin Email', input_html: { value: '' } %>
<%= club.inputs for: [:club_profile_attributes] do |ff| %>
<%= ff.input :country_id, as: :select, collection: Country.get_id_and_name, include_blank: false %>
<%= ff.input :logo, as: :file %>
<%= ff.input :email, label: 'Club Email' %>
<%= ff.input :phone_number_1, label: 'Phone Number' %>
<% end %>
<%= club.actions %>
<% end %>
Now how do I use an ajax request to update my users in dashboard.rb file, so whenever I create a club my user list gets updated using the ajax request/response.
$('#form_id').on('ajax:success', function(event, data, status, xhr){});
ajax:success and other custom events can be used to handle responses from remote: true forms. You would need to send the updated user list with the response data and then append or replace the user list.

Dropdown box selection to populate textbox in form

I am encountering a minor problem with some javascripts/AJAX and i was hoping someone can help me or point me to the right direction.
What I am trying to do is to populate my per-carton-price-field using collection_select in the same form. This is an order form which is suppose to create an entry into my order table. Form view as below:
new.html.erb
<h1>Add a new order for <%= #customer.name %></h1>
<div class="row">
<%= form_for(#order) do |f| %>
<div class="col-md-6">
<%= render 'shared/error_messages', object: f.object %>
<%= f.hidden_field :customer_id, :value => #customer.id %>
<h3>Order Details</h3>
<%= f.label :address_id, "Delivery Address" %>
<%= f.collection_select :address_id, #addresses, :id, :select_address, :prompt => "Select delivery location",class: 'form-control' %></br>
<%= f.label :remark, "Order Remark" %>
<%= f.text_area :remark, class: 'form-control' %></br>
<h3>What items would you like to place?</h3>
<%= f.add_nested_fields_link :single_orders, "Add Product" %>
<%= f.nested_fields_for :single_orders do |builder| %>
<%= builder.collection_select :product_id, #products, :id, :select_product, {:prompt => "choose product"}, {:class => "product_selection form-control"} %>
<%= builder.text_field :ctn_price, placeholder: "Price/carton", id: "price", class: 'ctn_price_field form-control' %>
<%= builder.text_field :qty, placeholder: "Quantity",id: "quantity", class: 'form-control' %>
<%= builder.text_field :price, placeholder: "Amount", id: "total-amount", readonly: true, class: 'form-control' %>
<%= builder.remove_nested_fields_link %>
<% end %>
</div>
<%= f.submit "place order", class: "btn btn-primary" %>
<% end %>
</div>
I would like the collection_select:product_id to pull out all the products in the products table. When the user selects whichever product they want to order from the dropdown, the price for the selected product will populate the text_field:ctn_price.
product.rb
class Product < ActiveRecord::Base
has_many :special_prices, dependent: :destroy
has_many :single_orders
has_many :package_orders_products
before_save :upcase_stock_code
validates :name, presence: true, length: { maximum: 50 }
validates :stock_code, presence: true, length: { maximum: 20 }
validates :status, presence: true, length: { maximum: 10 }
validates :price, presence: true
private
def select_product
"#{name} - #{price}"
end
# Converts stock_code to all upper-case.
def upcase_stock_code
self.stock_code = stock_code.upcase
end
end
single_order.rb
class SingleOrder < ActiveRecord::Base
belongs_to :order
belongs_to :product
validates :order, presence: true
validates :product_id, presence: true
validates :qty, presence: true
validates :price, presence: true
validates :ctn_price, presence: true
end
Any help is appreciated as I have been stuck for days :(
Thanks for any help in advance.
You can do this using ajax call. Before that create a api to take product_id as input and render #product as output.
$("#product_selection_id").on('change', function(){
var product_id = $(this).val();
$.ajax({
method: "GET",
type: 'html',
url: "call_url_for_get_product_api_with_product_id",
cache: false,
success: function(data, textStatus, jqxhr) {
console.log("success");
}
});
});
Suppose your url_for_get_product_api goes to get_product action as a js request. so create a template with get_product.js.erb as follows
$('#ctn_price_field').val(#product.price)
#ihave not tested this code change this according to your requirements.
Note: Here i have given a pattern impliment this by your own. Thanks.

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?

How can i change checkbox in rails?

How can i set a check box to true or false.. I have tried all of these combinations:
<%= check_box_tag 'prefs[can_be_email_notified]', :id => 'user_preferences_can_email'%> Email
<%= check_box_tag 'prefs[can_be_email_notified]', '', :id => 'user_preferences_can_email'%> Email
<%= check_box_tag 'prefs[can_be_email_notified]', '', :checked =>'',:id => 'user_preferences_can_email'%> Email
tried to change the checkbox with these
document.getElementById("user_preferences_can_email").checked = true;
document.getElementById("user_preferences_can_email").value = true;
document.getElementById("user_preferences_can_email").checked.value = true;
Maybe i wasnt clear...
I have a set of values that are set to buttons and want to change the checkbox's to be checked or unchecked detirmed on the value set on the the button,
ie:
function doubleClickUser(can_email, can_screen) {
document.getElementById("user_preferences_can_email").checked = can_email;
document.getElementById("user_preferences_can_screen").checked = can_screen;
}
<button class="button" onclick="doubleClickUser('true','false')"><%= user[:email] %></button>
<%= check_box_tag 'prefs[can_be_email_notified]', :id => 'user_preferences_can_email'%> Email
<%= check_box_tag 'prefs[can_be_screen_notified]', :id => 'user_preferences_can_screen' %> Screen
Set the field's value in your controller or model, then simply include the element in the standard Rails form:
# controller
#pref = Pref.new (or Pref.find(params[:id])
# view
<%= form_for #pref do |f| %>
<%= f.label :can_be_email_notified %>
<%= f.check_box :can_be_email_notified %>
<% end %>
This will reflect whatever value of can_be_email_notified #pref has.
If you want to be checked try this:
EMAIL
<%= check_box_tag "email",params[:email].to_s , {:checked => true} %>
Also if you want to assing a value you can try this:
<%= check_box_tag "email", "5", params[:email].to_s == "5", {:checked => true} %>
Figured it out you have to set the status to false first
<%= check_box_tag 'prefs[can_be_email_notified]', '', false, :id => 'user_preferences_can_email' %> Email <br>
<%= check_box_tag 'prefs[can_be_screen_notified]', '', false, :id => 'user_preferences_can_screen' %> Screen <br>
<%= check_box_tag 'prefs[can_be_sms_notified]', '', false, :id => 'user_preferences_can_sms' %> Text </div></th>

Categories

Resources