Rails: Provide default value for the disabled select helper - ruby-on-rails

I have a select helper as seen below, I have disabled it and would like give "1" as default value, but couldnt find how?
<%= f.select :fuel_incl, [[t('shared.incl'),'1'],[t('shared.notInc'),'0']], {}, {class: "Select-control u-sizeFull fuel_incl", :disabled => true} %>
It is disabled so it should select 1 as default.
EDIT
I see that it works from the console;
<select class="Select-control u-sizeFull fuel_incl" disabled="disabled" name="boat[fuel_incl]" id="boat_fuel_incl">
<option selected="selected" value="1">Included</option>
<option value="0">Not Included</option></select>
but it does not send as params, when I take out disable true and select value send the form, it works..
EDIT2
anyways, I have solved it by giving only one select value as;
<%= f.select :fuel_incl,
[[t('shared.incl'),'1']],
{ selected: '1' },
{ class: "Select-control u-sizeFull fuel_incl" } %>

Add selected option:
<%= f.select :fuel_incl,
[[t('shared.incl'),'1'],[t('shared.notInc'),'0']],
{ selected: '1' },
{ class: "Select-control u-sizeFull fuel_incl", disabled: true } %>

Related

Rails select options dynamically changing based on another select (without ajax)

I have a form where a user selects a school, and then a qualification that the school provides:
<div class="row">
<div class="col-md-6">
<%= f.association :education_organization,
collection: EducationOrganization.active,
include_blank: true
%>
</div>
<div class="col-md-6">
<%= f.association :training_qualification,
collection: TrainingQualification.active,
include_blank: true
%>
</div>
</div>
I would like to dynamically scope the qualifications select to only show the qualifications available to the school that is selected.
I don't want to do an ajax call, I'd rather send the whole list at the start and have the client switch the select options offline.
What's the best way to do this?
I found a way, by initially loading all options, then storing the html options and filtering that list by the id of the association as a data attribute.
View:
<%= f.association :education_organization,
collection: EducationOrganization.active,
include_blank: true
%>
<%= f.association :training_qualification,
collection: TrainingQualification.active.map { |tq| [tq.name, tq.id, {data: {org: tq.education_organization.id}}] },
include_blank: true
%>
JS:
$(function(){
// this is a hack that lets the JS be included anywhere, but only run on pages with the relevant form
var qualifications_select = $('#user_training_qualification_id');
if(qualifications_select) {
// this stores all select options
var qualification_options = qualifications_select.html();
function updateQualSelect(qualifications_select) {
var selected_org_id = $('#user_education_organization_id :selected').val();
if(selected_org_id != '') {
var filtered_options = $(qualification_options).filter(`[data-org=${selected_org_id}]`);
qualifications_select.html(filtered_options);
} else {
qualifications_select.empty();
}
}
// this line filters the select when the other select changes
$('#user_education_organization_id').change(function() {
updateQualSelect(qualifications_select);
});
// this line filters the select on page load
updateQualSelect(qualifications_select);
}
})

How to get f.select for static hash value rails?

i have static hash :
STATUS_BRAND = {
active: "hoatdong",
deactive: "khonghoatdong",
}.freeze
my view:
= f.select :status, Brand::STATUS_BRAND, class: "form-control post-type input-bg"
i wanto display value in here is : "hoatdong" and "khonghotdong" in views
If you do not want the select to return the keys to Rails, then you have to invert the Hash:
f.select(:status, options_for_select(Brand::STATUS_BRAND.invert), ...)
Output:
<option value="active">hoatdong</option>
<option value="deactive">khonghoatdong</option>
You can look at the documentation for options_for_select for more examples.

Select box doesn't show selected value

I have a select box like this, it works and is saved in the database, but after I refresh the page the selected value doesn't appear as selected. Any suggestions?
.col-md-6
%span.label.label-purple{:style => "pointer-events: none; font-size: 14px"} Country Default
= select_tag :country_default, options_for_select(Location.where(loc_type: "country").map { |country| [country.name, country.loc_code] }),
style: "margin-top: 11px;",
include_blank: "",
class: "country-default select2", data: { select: "select2"}
options_for_select has an optional second argument, which will display your selected option, if one has been selected.
...options_for_select(Location.where(loc_type: "country").map { |country|
[country.name,
country.loc_code]}, #YOURMODEL.country_default)...
Use collection_select instead of select_tag like this:
=collection_select :country, :default, Location.where(loc_type: "country"), :loc_code, :name,
{include_blank: '', selected: 'select2' },
{class: 'country-default select2', style: 'margin-top: 11px;'}
another option is using select to generate select boxes.
See the Action View Helpers Guide

Select option required Ruby Rails

I have a mix of ruby rails code
I have a form with a selection option that i want to be a required, and i want to validate. If user do not select anything i want to validade with a error message.
However, I try to copy past code from internet, I'm new at ruby rails and I still not have a error message.
I also check that i use 'required' , or if i use 'validates_presence_of' doesn't make difference because it's a submit form (i think)
test_filteR_form.rb
class TestFilterForm < ApplicationForm
attribute :model, String
validates_presence_of :model
end
.html.erb
<%= f.input :fill_form_error_message,:as => :hidden, :input_html => { :value =>I18n.t('test.fill_form_error') } %>
<%= f.input :model, label: I18n.t('test.filters.model'), autofocus: true, input_html: {class: 'input-xlarge chosen-select' }, collection: TestType.options_for_select, include_blank: true %>
"/>
controller
def paginate
#test_form = TestForm.new(params)
unless #test_form.valid?
#model = params[:test_filter_form][:model]
#h_model = #model.pluralize + 'H'
#history, _query, #test_fields = TestQueryService.search!(params)
session[:test_query] = _query
session[:test_klass] = #model
else
format.json { render :json => { :error => #test_form.errors.full_messages }, :status => 422 }
end
js.coffee
$contentDiv.on 'ajax:error', 'form[data-value]', (event, xhr, status, error) ->
data = $.parseJSON(xhr.responseText)
$result = $(#).parents('tr').find('[data-result]')
controller.resultUpdateError xhr.status, $result.data('result'), data, $(#)
# Hide row loading spinner
$(#).parents('tr').find('span[role="result_update_spinner"]').hide()
# Hide saved form
$(#).parents('tr').find('.saved_form').hide()
resultUpdated: (result, data, $form) ->
if data.flash != undefined
# Sets a sucess message on page top
flash data.flash.type, data.flash.message
# Sets a success message on row
$fieldForm = $form.parents('tr').find(".messages")
$fieldForm.find('.controls').empty()
$fieldForm.find('.control-group .controls').css('color', 'green').append #_inlineMessage("Gravado com sucesso")
# Hide success message after some time
setTimeout ((self) ->
->
$fieldForm.find('.control-group .controls').empty()
return
)(this), 4000
Since you are dynamically created the selection box then there must be a default value selected which is not nil so there is no change seen you can manually create selection like this:
<div class="form-group">
<%= f.label :select_user_country %><br/>
<select class="form-control select2" name="user[country_id]">
<option value="" selected disabled>Select a Country</option>
<%#countries.each do |country|%>
<option value="<%=country.id%>"><%=country.name%></option>
<%end%>
</select>
</div>

select_tag helper with grouped_options_for_select order

I have this in my model:
LOCATION_IN_UK = {'England' => [['Berkshire', 1],['Cambridgeshire',2],['Cheshire',3]], 'Scotland' => [['Dumfries and Galloway',4],['Fife',5],['Lothian',6]], 'Others' => [['Outside UK',7]]}
And this is in the view:
<%= select_tag :location, grouped_options_for_select(Location::LOCATION_IN_UK), :id => 'location-dropdown' %>
This code generate following html:
<select id="location-dropdown" name="location">
<optgroup label="England">
<option value="1">Berkshire</option>
<option value="2">Cambridgeshire</option>
<option value="3">Cheshire</option></optgroup>
<optgroup label="Others">
<option value="7">Outside UK</option></optgroup>
<optgroup label="Scotland">
<option value="4">Dumfries and Galloway</option>
<option value="5">Fife</option>
<option value="6">Lothian</option></optgroup>
</select>
1. How to skip alphabetical sort order. I want elements locate exactly as in the hash LOCATION_IN_UK.
2. How to insert prompt into this? :prompt => 'Please select' Doesn't work
To answer your prompt question, prompt is not a hash, it is the third parameter of the method call. So you would do:
<%= select_tag :location, grouped_options_for_select(LOCATIONS_IN_UK, nil, "Please Select"), :id => 'location-dropdown' %>
And looking at the source code, it seems there is no way to skip the sorting. You could write your own helper method though. Here is the source
# File actionpack/lib/action_view/helpers/form_options_helper.rb, line 449
def grouped_options_for_select(grouped_options, selected_key = nil, prompt = nil)
body = ''
body << content_tag(:option, prompt, { :value => "" }, true) if prompt
grouped_options = grouped_options.sort if grouped_options.is_a?(Hash)
grouped_options.each do |group|
body << content_tag(:optgroup, options_for_select(group[1], selected_key), :label => group[0])
end
body.html_safe
end
You could modify/override that method, but that may break if you are using this function elsewhere, which is why I would suggest you put the following in your application_helper.
def unsorted_grouped_options_for_select(grouped_options, selected_key = nil, prompt = nil)
body = ''
body << content_tag(:option, prompt, { :value => "" }, true) if prompt
##Remove sort
#grouped_options = grouped_options.sort if grouped_options.is_a?(Hash)
grouped_options.each do |group|
body << content_tag(:optgroup, options_for_select(group[1], selected_key), :label => group[0])
end
body.html_safe
end
You can then call unsorted_grouped_options_for_select and it should work.
<%= select_tag :location, unsorted_grouped_options_for_select(LOCATION::LOCATION_IN_UK, nil, "Please Select"), :id => 'location-dropdown' %>
I had the same problem. You can solve this by using the array version instead of hashes since it only orders it if it is_a?(Hash).
See the docs for the format: http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/grouped_options_for_select

Resources