simple_form checkboxes collection with "other" checkbox - ruby-on-rails

I use simple_form and have this in my form code:
<%= f.input :fruit, as: :check_boxes, collection: ['Apple', 'Orange', 'Other'] %>
So I want to have a text input associated with 'Other' field next to it, so that user can click 'Other' and enter his own fruit name. How do I do it?
I tried it like f.input(...) as one of collection items, I've also tried adding it in do block, but it all seems like totally irrelevant.
How do I get the behavior I want? Thank you.

You can do this:
# view
<%= text_field_tag :alternative_fruit %>
# controller
if params[:alternative_fruit].present? && params[:your_model_name][:fruit].select(&:present?).blank?
params[:your_model_name][:fruit] = params[:alternative_fruit]
end
This will overwrite the fruit name if you didn't select a checkbox with the alternative name, if you defined one.

Related

Field gets radio button's item id instead of its value

I have snippet:
<%= f.input :purpose, as: :radio_buttons, collection: category.subcategories,
wrapper: :vertical_collection_inline %>
which lines values of category.subcategories horizontally how I want
The problem is, when I select either of option, it assigns that option's ID, but not its value.
How should I refactor the code?
Using IDs has advantages as warned in the comments, however what you’re trying to do should work with either:
category.subcategories.collect(:&values)
Where values is the name of the field which hols “Rent” etc.
The more railsy way to do this is with collection_radio_buttons, like this:
f.collection_radio_buttons(:purpose, category.subcategories, :value, :value)
Again where “value” is the field name.

Rails 4 - Display choices as radio buttons

I am working on a Rails 4 application, using simple_form for input. There are several model fields that can take well-known answers or a free-form answer. For example, for a field fruit:string I would like to display "Apple", "Banana", "Other". If the user chooses "Other", they can enter any free-form text. Currently, all I can do is use <%= f.input :fruit %> and a blank textbox shows up. Is it possible to show radio buttons instead? I can do
<%= f.collection_radio_buttons :fruit, [["Apple", "Apple"], ["Banana", "Banana"]], :first, :last %>
but that does not provide the "Other" option. The goal is to record "Apple", "Banana" or the specified (typed-in) value if "Other" was chosen.
Simple Form lets you us as: :radio_buttons on a collection, like so
<%= f.input :fruit, collection: ['apple', 'banana', 'other'], as: :radio_buttons %>
See the collection section of the SimpleForm README for more information on collection inputs.
One solution would be to have the f.collection_radio_buttons followed by the f.input, both with the same name. Then, selectively enable the f.input based on the selected radio button with jquery or javascript. For this to work, you would probably also want to add an ['Other']['Other'] option.
EDIT
Maybe something along these lines:
f.collection_radio_buttons :fruit, [['Apple','Apple'],['Orange','Orange'],['Other','Other']], :first, :last
f.text_field :fruit
$("input:radio[name='foo[fruit]']").change(function(){
if($(this).val() == 'Other'){
$("input:text[name='foo[fruit]']").show().prop( "disabled", false);
}else{
$("input:text[name='foo[fruit]']").hide().prop( "disabled", true );
}});
Because they have the same name, Rails will use the last value (the text field in this case if it is enabled), otherwise it will use the selected radio button.

Form_for select field, concatenating data into the display string

I am trying to use a form_for collection_select to display some select field options of account types.
Its occurred to me that it would be easier for the user if they could see the price of the type in each select option
this is my currently not-working code:
<%= a.collection_select :account_type, AccountType.all, :id, (:name+" - "+number_to_currency(:price)) %>
how can i concatenate the values so that (:name+" - "+number_to_currency(:price)) will actually work and not throw an error?
See the documentation:
http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select
You can use the :text_method option to set the displayed text in the select dropdown.
In your AccountType model, define a method like this:
def name_with_price
"#{name} - $#{price}"
end
Then, in your view, you can use:
<%= a.collection_select :account_type, nil, AccountType.all, :id, :name_with_price %>

how do you group select_tag and text_field_tag?

I'm trying to build a form where a user can select an existing category, or define their own.
My form looks something like this...
<%= f.select :category, category_options, prompt: "Select">
<%= f.text_field :category %>
However, this UI is confusing. The user can select something in the select box, and type in a custom category. In this case, the final result is not obvious.
Do you guys have any recommendations on how to handle this situation?
By default, text field will be hidden and disabled
Dropdown should have "OTHER" option
when user selects "OTHER" option,
text field will be enabled and displayed,then user should be able to enter value there.

rails form - 2 fields with same id in a form - how to disable second field when first field is selected

I have in my rails form the following code:
<label>Fruit: </label> <%= f.select(:IST_FRUIT, [['Apple', 'Apple'],
['Orange', 'Orange'],
['Kiwi', 'Kiwi'],
['Other', 'Other']
],{ :prompt => "Please select"},{:onchange => "if (this.value == 'Other')
{document.getElementById('otherTissue').style.display = 'block';
} "}
) %>
<span id="otherFruit" style="display:none;"> If other, please state: <%= f.text_field :IST_FRUIT, :size => 10 %></span>
User can select a fruit form the listbox but if user selects 'Other', a textfield is diaplayed allowing user to input his value.
The problem is that when user selects a fruit and save the form, the fruit field in blank in the table and the reason is that the form is saving the second field 'IST_FRUIT' found in the span with id 'IST_FRUIT'.
I would be really grateful if someone could show me a way how to disable the second field when 'other' is not selected and enable it when 'Other' is selected from the dropdown list.
Many many thanks for any suggestion provided.
First, be aware that rails posts are based on fields' name, not ids.
In your case, you should use a virtual attribute to store the potential other fruit value.
Your model could look like:
attr_accessor :other_fruit
before_save :check_fruits
def check_fruits
#if other_fruit is not nil, it means that you want to store it's value in you IST_FRUIT column
#BTW, why these capital letters?
IST_FRUIT = other_fruit unless other_fruit.nil?
end
And your form would be:
<span id="otherFruit" style="display:none;"> If other, please state: <%= f.text_field :other_fruit, :size => 10 %></span>
I have another advice. Instead of disabling a HTML input (by the way - an ID must be unique in a HTML document) just make another attribute in your model, name it 'other_fruit' for example, and use this value if the 'fruit' is set to 'other' or is empty. For example you may write something like this:
class TheModel
attr :other_fruit
# Overwritten accessor for the fruit attribute.
# Returns the values of :other_fruit if :fruit is blank.
#
def fruit
if self[:fruit].blank?
other_fruit
else
self[:fruit]
end
end
end
Now the HTML part. In your JavaScript you set 'display' to block, but you do not reset it when user selects another option.
If you want to prevent the field from being sent to the server, you should set the 'disabled' attribute. Setting the 'style' only hides the control from the user's eyes.

Resources