How to prevent input from sending params - ruby-on-rails

I have two inputs, both use the same field in the database. The difference between them is simple, one is just text input while the other makes it possible for the user to pick something from dropdown list. Might look like this:
= f.input :age, :label => false, input_html: {class: "textfield"}
= f.input :age, :label => false, input_html: {class: "dropdown"}, collection: [1,2,3]
in this case, only the second input will send information.
My question is: How can I prevent input from sending anything WITHOUT removing it from HTML?
(my purpose is to enable user pick option "custom age" which will enable them to fill the field with, well, custom value. tricky part is both input must be there all the time)

If you disable an input, its value is not sent when you submit the form. So you could use an onSubmit event on the form to disable the right input before the form is submitted.
With jQuery, it would look like this:
$('form').on('submit', function() {
var textInput = ...;
var dropdownInput = ...;
if (textInput.val() == '') {
textInput.prop('disabled', true);
} else {
dropdownInput .prop('disabled', true);
}
});

Related

Rails/ActiveAdmin form: how to disable an input field based on the value of another (boolean) input field?

I have a model that has a boolean field and an array field that gets the values populated from another model (foreign key, not really relevant to my question).
In ActiveAdmin, I have a form like such:
form do |f|
f.semantic_errors
f.inputs do
f.input :boolean_field_name
f.input :array_field_name,
as: :searchable_select,
ajax: true,
input_html: { disabled: true }
end
f.actions
end
The disabled: true works, but I would like to replace the true with something that evaluates whether or not the input checkbox for boolean_field_name has been checked on the form (which by default it isn't).
I've tried params[:boolean_field_name], params.key?[:boolean_field_name], f.object.boolean_field_name, f.object[:boolean_field_name], resource[:boolean_field_name] and resource.boolean_field_name, but they all do nothing and evaluate to nil as far as I can tell.
I've even tried ModelName.find(params[:id]).boolean_field_name but of course since params[:id] is nil that doesn't work, and it wouldn't find a record with that id anyway because the record hasn't been created yet.
I've tried looking through the ActiveAdmin repository but I can't find the information I'm looking for in the source code either.
Is this even possible?
Did you mean like this?
form do |f|
f.semantic_errors
f.inputs do
f.input :boolean_field_name
f.input :array_field_name,
as: :searchable_select,
ajax: true,
input_html: { disabled: f.object.boolean_field_name # <= does not work }
end
f.actions
end
Since the information is a bit ambiguous to me, I would firstly like to know:
From the description:
The disabled: true works, but I would like to replace the true with
something that evaluates whether or not the input checkbox for
boolean_field_name has been checked on the form (which by default it
isn't).
Did you mean that you wanna change the disabled attribute depending on the other form field after the page loads? If that's true, then you have to do it with javascript as something like this:
let booleanField = document.querySelector('booleanField'),
arrayField = document.querySelector('arrayField');
booleanField.addEventListener('change', function(e) {
arrayField.setAttribute('disabled', booleanField.value);
})
Or if you mean you just wanna set the value of the disabled attribute to what boolean_field initially is on page loads, it will bring us more information if you can debug with the tools like debug, debugger or binding.pry. It will be helpful to checkout what f.object.boolean_field_name returns. According to the information you provides, I guess it could really be nil.

Disabled Haml field is not passed to my rb file

I have a single form which has some input fields. This form, firstly get values from database and fill them in. If they have value they will be disabled.
=text_field_tag("dt|#{a_key}",(begin;a_mock["dt_open"];rescue;nil;end), :class => "form-control", :disabled => a_mock["active"] == "true" )
In my rb file there is a rule which validate date. If the field is blank:
if !dt_open.blank?
...
end
What I noticed is if the field are disabled, it doesn't send. I know because I print the message and the field aren't there.
How can overcome this behavior in haml?
Input with disabled attribute will not submitted, you can user readonly rather disabled, did the almost same thing you can not change or edit input field value.
Another solution
If you still want to use the disabled attribute the you can apply the following javascript to allow submit the disabled
<script>
$('#your_form_id').submit(function() {
$("#disabled_input_field_id").prop('disabled', false);
//your code goes here
})
</script>
You can use a hidden_field_tag that will post the value on submit. I would also just print the value in a p tag instead of showing a disabled text input, but that is just my opinion.
- if a_mock["active"] == "true"
= hidden_field_tag "dt|#{a_key}", a_mock["dt_open"]
p= a_mock["dt_open"]
- else
= text_field_tag "dt|#{a_key}", a_mock["dt_open"], class: "form-control"

Adding a tag if it doesn't exist in rails chosen rails

I have implemented the functionality of adding tags to a post in Rails using chosen-rails and acts-as-taggable gems. I want to further enhance the functionality by making user to create new tag if it doesn't exist.
form.html.slim
.form-group.text-center
= f.label :tag_ids, "Tags"
= f.collection_select :tag_ids, Tag.order(:name), :id, :name, {}, {multiple: true}
I need to add a new tag if it doesn't exist.
Ok with Selectize.js, Acts_as_Taggable, & SimpleForm:
Firstly, change your input from collection_select to a normal string input. Selectize.js will separate all of the values into tags anywhere there is a comma. This happens behind the scenes so as people add tags, it's actually inserting a long string into your database with whatever delimiter you supply. Then you need to add an id to that field so you can initialize selectize such as:
<%= f.input :nationalities, as: :string, placeholder: "Nationalities", input_html: { id: 'nationality-input'} %>
Then initialize selectize.js:
#The following line gets all tags ever posted for a user with the context 'nationalities' which we will use as options.
<%=nations = ActsAsTaggleOn::Tagging.includes(:tag).where(context: 'nationalities').uniq.pluck(:id, :name)
$(document).ready(function() {
$('#nationality-input).selectize({
delimiter: ',',
persist: true,
allowEmptyOption: false,
options: [
<% nations.each do |nat| %>
{text: '<%=nat[1] %>', value: '<%=nat[1]%>' },
<% end %>
searchField: 'text',
create: function(input) {
return {
value: input,
text: input
}
}
});
});
Make sure you have acts_as_taggable setup properly and that the corresponding model includes it. Then in your controller just save the whole string with commas and all and allow selectize to reformat it on views automagically.

Ruby Simple Form Checkbox not checking when True

So I have multiple checkboxes made using simple form a Ruby Gem. But the issue is that they are not appearing checked even when I have checked and set them "true" and pressed the update button. I have three examples, all of them do not work, and I have tried doing different code for all three.
<%= f.input :same_as_client_email,
inline_label: "Same as Client Email",
as: :boolean %>
The first example
<%= f.input :same_as_client_name,
inline_label: "Same as Client Name",
as: :boolean, checked_value: true,unchecked_value: false
%>
Second example
<%= f.input :active,
as: :boolean,
checked_value: true, unchecked_value: false,
input_html: { value: '1', checked: true },
inline_label: "Active"%>
Final example.
None of these actual work or stay checked. I have other inputs and they are saving when I press the update button. But the check boxes are not. Any help would be appreciated.
It was a javascript problem just in case anyone else comes along and sees this. Be carful using jquery and simpleform together. My problem was that we had jquery code to make our buttons more aesthetically appealing.
//$(function checkbox() {
// 'use strict'
//
// var originalElement = $('input[type="checkbox"]');
// var overlay = '<div class="checkbox-overlay"><div class="inner"></div></div>';
//
// function swapCheckbox() {
// originalElement.replaceWith(overlay);
// }
//
// function toggleCheckbox() {
// $(this).toggleClass('checked');
//
// }
//
// function initialize() {
// swapCheckbox();
// $('body .checkbox-overlay').on('click', toggleCheckbox);
// }
//
// initialize();
//});
But in reality this was making it so simpleform was receiving only 0, and never 1's. In ohter words even if you checked the box it would never actually work because this Jquery code was manipulating the variables as they were sent to simpleform. In the future Ill update this post if i fix the checkboxes so they can look "pretty" while not messing with the functionality. This problem took a long time to solve, considering i was unaware of this file till a SimpleForm developer pointed out their might be a js file messing with my code.
Edit: I hope this explains the problem better!

simple_form doesnt prevent sending request without required fields

i have this form
= simple_form_for #category.fields.build, url: category_fields_path(#category) do |f|
= f.input :kind, collection: Field::FIELD_TYPES, prompt: "Choose field type"
= f.input :description
= f.submit "Add field"
and this field model
class Field < ActiveRecord::Base
FIELD_TYPES = %w(integer float date string text)
validates :description, presence: true
validates :kind, presence: true
belongs_to :category
end
when i leave 'description' field empty, no request is send and i get notice 'Please fill out this field'. which is what i want. on the other hand, when description is filled in but kind is not, a request is still send to the 'create' action! No field gets created, but 'description' needs to be filled in again. there should be no request in such situation. any idea how to fix this?
Though, I don't have exact answer to Your problem, but You should start with checking HTML output. Simple from relies on HTML5 to provide front-end validation. All inputs should have required attribute, to have validation enabled. Maybe there is a bug, and in this particular case simple_form does not output required attribute.
Another thing to take in account as it is HTML5, consult browser support: http://caniuse.com/#feat=form-validation . Theoretically it's possible that You are testing on browser that has limited support for form validations.
If You discover that simple_from did not output required for Your kind fuel, try forcing it:
= f.input :kind, collection: Field::FIELD_TYPES, prompt: "Choose field type", required: true
I got my answer at Simple Form github's issue topichere. to sum up, problem was prompt, validation is not (yet?) working with it correctly, solution is to replace it, eg like this:
= f.input :kind, collection: Field::FIELD_TYPES, include_blank: "Choose field type", label: false

Resources