Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add multiple option for select #526

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 56 additions & 8 deletions lib/assets/javascripts/best_in_place.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,14 @@ BestInPlaceEditor.prototype = {
this.previousCollectionValue = value;

// search for the text for the span
$.each(this.values, function(index, arr){ if (String(arr[0]) === String(value)) editor.element.html(arr[1]); });
if (this.selectMultiple) {
var selectedValues = this.values.map( function(v) { if (value.indexOf(v[0]) > -1) { return v[1] } })
.filter( function(v) { return v != undefined } )
editor.element.html(selectedValues.join(','));
}
else {
$.each(this.values, function(index, arr){ if (String(arr[0]) === String(value)) editor.element.html(arr[1]); });
}
break;

case "checkbox":
Expand Down Expand Up @@ -189,6 +196,7 @@ BestInPlaceEditor.prototype = {
self.cancelButton = self.element.data("bipCancelButton") || self.cancelButton;
self.cancelButtonClass = self.element.data("bipCancelButtonClass") || self.cancelButtonClass || BestInPlaceEditor.defaults.cancelButtonClass;
self.skipBlur = self.element.data("bipSkipBlur") || self.skipBlur || BestInPlaceEditor.defaults.skipBlur;
self.selectMultiple = self.element.data("bipSelectMultiple");

// Fix for default values of 0
if (self.element.data("bipPlaceholder") == null) {
Expand Down Expand Up @@ -254,7 +262,17 @@ BestInPlaceEditor.prototype = {
csrf_param = jQuery('meta[name=csrf-param]').attr('content');

var data = "_method=" + BestInPlaceEditor.defaults.ajaxMethod;
data += "&" + this.objectName + '[' + this.attributeName + ']=' + encodeURIComponent(this.getValue());

var value = this.getValue()

if (jQuery.isArray(value)) {
for (var i in value) {
data += "&" + this.objectName + '[' + this.attributeName + '][]=' + encodeURIComponent(value[i]);
}
}
else {
data += "&" + this.objectName + '[' + this.attributeName + ']=' + encodeURIComponent(value);
}

if (csrf_param !== undefined && csrf_token !== undefined) {
data += "&" + csrf_param + "=" + encodeURIComponent(csrf_token);
Expand Down Expand Up @@ -458,27 +476,48 @@ BestInPlaceEditor.forms = {
.attr('style', 'display:inline'),
selected = '',
select_elt = jQuery(document.createElement('select'))
.attr('class', this.inner_class !== null ? this.inner_class : ''),
.attr('class', this.inner_class !== null ? this.inner_class : '')
.attr('multiple', this.selectMultiple),
currentCollectionValue = this.collectionValue,
key, value,
a = this.values;
var _self = this;

$.each(a, function(index, arr){
key = arr[0];
value = arr[1];
var option_elt = jQuery(document.createElement('option'))
.val(key)
.html(value);
if (String(key) === String(currentCollectionValue)) option_elt.attr('selected', 'selected');

if (_self.selectMultiple) {
if (currentCollectionValue && currentCollectionValue.indexOf(String(key)) > -1) option_elt.attr('selected', 'selected');
}
else {
if (String(key) === String(currentCollectionValue)) option_elt.attr('selected', 'selected');
}

select_elt.append(option_elt);
});
output.append(select_elt);

if (this.selectMultiple) {
if (!this.okButton) this.okButton = 'submit'
this.placeButtons(output, this);
}

this.element.html(output);

if (this.selectMultiple) {
this.element.find("form").bind('submit', {editor: this}, BestInPlaceEditor.forms.input.submitHandler)
}
else {
this.element.find("select").bind('change', {editor: this}, BestInPlaceEditor.forms.select.blurHandler);
this.element.find("select").bind('blur', {editor: this}, BestInPlaceEditor.forms.select.blurHandler);
this.element.find("select").bind('keyup', {editor: this}, BestInPlaceEditor.forms.select.keyupHandler);
}

this.setHtmlAttributes();
this.element.find("select").bind('change', {editor: this}, BestInPlaceEditor.forms.select.blurHandler);
this.element.find("select").bind('blur', {editor: this}, BestInPlaceEditor.forms.select.blurHandler);
this.element.find("select").bind('keyup', {editor: this}, BestInPlaceEditor.forms.select.keyupHandler);
this.element.find("select")[0].focus();

// automatically click on the select so you
Expand All @@ -495,7 +534,16 @@ BestInPlaceEditor.forms = {

getValue: function () {
'use strict';
return this.sanitizeValue(this.element.find("select").val());
var val = this.element.find("select").val();
if (this.selectMultiple) {
var _self = this;
return val.map( function(v) {
return _self.sanitizeValue(v);
})
}
else {
return this.sanitizeValue(val);
}
},

blurHandler: function (event) {
Expand Down
12 changes: 9 additions & 3 deletions lib/best_in_place/helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,14 @@ def best_in_place(object, field, opts = {})

if opts[:collection] or type == :checkbox
collection = opts[:collection]
value = value.to_s
collection = best_in_place_default_collection if collection.blank?
collection = best_in_place_collection_builder(type, collection)
display_value = collection.flat_map{|a| a[0].to_s == value ? a[1] : nil }.compact[0]
if value.is_a? Array
display_value = collection.flat_map{|a| value.include?(a[0].to_s) ? a[1] : nil }.compact.join(',')
else
value = value.to_s
display_value = collection.flat_map{|a| a[0].to_s == value ? a[1] : nil }.compact[0]
end
collection = collection.to_json
options[:data]['bip-collection'] = html_escape(collection)
end
Expand Down Expand Up @@ -53,6 +57,8 @@ def best_in_place(object, field, opts = {})
options[:data]['bip-confirm'] = opts[:confirm].presence
options[:data]['bip-value'] = html_escape(value).presence

options[:data]['bip-select-multiple'] = opts[:multiple].presence

if opts[:raw]
options[:data]['bip-raw'] = 'true'
end
Expand Down Expand Up @@ -82,7 +88,7 @@ def pass_through_html_options(opts, options)
:activator, :cancel_button, :cancel_button_class, :html_attrs, :inner_class, :nil,
:object_name, :ok_button, :ok_button_class, :display_as, :display_with, :path, :value,
:use_confirm, :confirm, :sanitize, :raw, :helper_options, :url, :place_holder, :class,
:as, :param, :container]
:as, :param, :container, :multiple]
uknown_keys = opts.keys - known_keys
uknown_keys.each { |key| options[key] = opts[key] }
end
Expand Down
13 changes: 13 additions & 0 deletions lib/best_in_place/test_helpers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,19 @@ def bip_select(model, attr, name)
wait_for_ajax
end

def bip_multi_select(model, attr, opts, unselect=[])
id = BestInPlace::Utils.build_best_in_place_id model, attr
find("##{id}").trigger('click')
opts.each do |opt|
find("##{id}").select(opt)
end
unselect.each do |opt|
find("##{id}").unselect(opt)
end
find("##{id} input[type=submit]").trigger('click')
wait_for_ajax
end

def wait_for_ajax
return unless respond_to?(:evaluate_script)
wait_until { finished_all_ajax_requests? }
Expand Down
27 changes: 27 additions & 0 deletions spec/integration/js_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,33 @@
expect(find('#country')).to have_content('France')
end

it "should be able to use bip_multi_select to render and update a multi-select field" do
@user.favorite_snacks = %w(whoppers sun-chips)
@user.save!
visit user_path(@user)

expect(find('#favorite_snacks')).to have_content('Whoppers,Sun Chips')

bip_multi_select @user, :favorite_snacks, ['Twizzlers','Kettle Corn'], ['Sun Chips']

expect(find('#favorite_snacks')).to have_content('Twizzlers,Whoppers,Kettle Corn')
expect(find('#favorite_snacks')).not_to have_content('Sun Chips')
visit user_path(@user)

expect(find('#favorite_snacks')).to have_content('Twizzlers,Whoppers,Kettle Corn')
end

it "does not error when value is nil" do
@user.save!
visit user_path(@user)
expect(find('#favorite_snacks')).to have_content('-')

bip_multi_select @user, :favorite_snacks, ['Sun Chips']
expect(find('#favorite_snacks')).to have_content('Sun Chips')
visit user_path(@user)
expect(find('#favorite_snacks')).to have_content('Sun Chips')
end

it "should apply the inner_class option to a select field" do
@user.save!
visit user_path(@user)
Expand Down
5 changes: 5 additions & 0 deletions spec/internal/app/assets/stylesheets/application.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/*
*= require scaffold.css
*= require style.css
*= require jquery-ui-1.8.16.custom.css
*/
4 changes: 4 additions & 0 deletions spec/internal/app/helpers/users_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,8 @@ def height_collection
def bb(value)
"#{value} €"
end

def snacks_options
Hash[ ["Twizzlers", "Whoppers", "Krispy Kremes", "Sun Chips", "Kit Kat", "Kettle Corn"].map { |o| [o.downcase.gsub(/\s+/, '-'), o] } ]
end
end
3 changes: 3 additions & 0 deletions spec/internal/app/models/user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ class User < ActiveRecord::Base
alias_attribute :receive_email_image, :receive_email
alias_attribute :description_simple, :description

serialize :favorite_snacks

def address_format
"<b>addr => [#{address}]</b>".html_safe
end
Expand All @@ -32,4 +34,5 @@ def markdown_desc
def zip_format
nil
end

end
2 changes: 1 addition & 1 deletion spec/internal/app/views/layouts/application.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<html>
<head>
<title>Best In Place TEST APP <%= Rails::VERSION::STRING %></title>
<%= stylesheet_link_tag "scaffold", "style", "jquery-ui-1.8.16.custom" %>
<%= stylesheet_link_tag "application" %>
<%= javascript_include_tag "application" %>
<%= csrf_meta_tag %>
</head>
Expand Down
6 changes: 6 additions & 0 deletions spec/internal/app/views/users/show.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,12 @@
<%= best_in_place @user, :favorite_movie, opts %>
</td>
</tr>
<tr>
<td>Favorite snacks</td>
<td id="favorite_snacks">
<%= best_in_place @user, :favorite_snacks, as: :select, multiple: true, collection: snacks_options %>
</td>
</tr>
<tr>
<td>Zero Field</td>
<td id="zero_field">
Expand Down
1 change: 1 addition & 0 deletions spec/internal/db/schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,6 @@
t.string "favorite_movie"
t.string "favorite_locale"
t.integer "zero_field"
t.string "favorite_snacks"
end
end
8 changes: 6 additions & 2 deletions spec/rails_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,12 @@

require 'best_in_place'

Combustion.initialize! :active_record, :action_controller,
:action_view, :sprockets
Combustion.initialize! :active_record, :action_controller, :action_view, :sprockets do
config.assets.compile = true
config.assets.compress = false
config.assets.debug = false
config.assets.digest = false
end

require 'rspec/rails'
require 'capybara/rails'
Expand Down