ExtJS - Navigate through ComboBox with prev/next buttons - extjs

I'm designing a custom control to look something like this:
I've got the ComboBox loading the Store fine, but what I'm trying to do is use the arrows to select the next and previous values in the Combo. I've set the valueField on the Combo to be the "id" from the Store, which are not incremental in fashion.
I've tried something like this:
// this gets the current record
var currentBanner = this.bannersComboBox.getStore().getById(this.bannersComboBox.getValue());
// this gets the current records index in the store
var currentStoreIndex = this.bannersComboBox.getStore().indexOf(currentBanner);
The problem is that setValue() on the ComboBox requires the "value", and in this case I need to just do a simple setValue(currentValue + 1 [-1]), or something of that nature. How would you increment the combo when the values aren't incremental?
This would be really easy if there was a selectNext() or something method on the Combo!

Figured it out. :)
var currentBanner = this.bannersComboBox.getStore().getById(this.bannersComboBox.getValue());
var currentStoreIndex = this.bannersComboBox.getStore().indexOf(currentBanner);
var nextBannerValue = this.bannersComboBox.getStore().getAt(currentStoreIndex + 1).get('id')
this.bannersComboBox.setValue(nextBannerValue);

I prefer to use select() rather than setValue(). Here's the code to select the next combobox item:
function comboSelectNextItem( combo, suppressEvent ) {
var store = combo.getStore();
var value = combo.getValue();
var index = store.find( combo.valueField, value );
var next_index = index + 1;
var next_record = store.getAt( next_index );
if( next_record ) {
combo.select( next_record );
if( ! suppressEvent ) {
combo.fireEvent( 'select', combo, [ next_record ] );
}
}
}
Code to select the previous combobox item:
function comboSelectPrevItem( combo, suppressEvent ) {
var store = combo.getStore();
var value = combo.getValue();
var index = store.find( combo.valueField, value );
var prev_index = index - 1;
var prev_record = store.getAt( prev_index );
if( prev_record ) {
combo.select( prev_record );
if( ! suppressEvent ) {
combo.fireEvent( 'select', combo, [ prev_record ] );
}
}
}
You could also extend Ext.form.field.ComboBox to include those functions (with minor changes). For example you can place this code in the launch() function of your application, so that any Ext.form.field.Combobox inherits of those two methods:
Ext.define( "Ext.form.field.ComboBoxOverride", {
"override": "Ext.form.field.ComboBox",
"selectNextItem": function( suppressEvent ) {
var store = this.getStore();
var value = this.getValue();
var index = store.find( this.valueField, value );
var next_index = index + 1;
var next_record = store.getAt( next_index );
if( next_record ) {
this.select( next_record );
if( ! suppressEvent ) {
this.fireEvent( 'select', this, [ next_record ] );
}
}
},
"selectPrevItem": function( suppressEvent ) {
var store = this.getStore();
var value = this.getValue();
var index = store.find( this.valueField, value );
var prev_index = index - 1;
var prev_record = store.getAt( prev_index );
if( prev_record ) {
this.select( prev_record );
if( ! suppressEvent ) {
this.fireEvent( 'select', this, [ prev_record ] );
}
}
}
});
Then you could use those methods anywhere in your code:
var combo = ... // the combo you are working on
combo.selectNextItem(); // select the next item
combo.selectPrevItem(); // select the previous item

Related

Isotope: Combined multiple checkbox and searchbox filtering

I'm trying to combine the Isotope multiple checkbox filtering with a searchbox.
I used the example with the checkbox filters from here and tried to implement the searchbox but with no luck.
Just the checkbox filtering works well. I think i'm close to the solution but my javascript skills are at a very beginner level.
I commented out the section of what i've tried to implement.
Thank you for some hints
// quick search regex
var qsRegex;
var $grid;
var filters = {};
var $grid = $('.grid');
//set initial options
$grid.isotope({
layoutMode: 'fitRows'
});
$(function() {
$grid = $('#grid');
$grid.isotope();
// do stuff when checkbox change
$('#options').on('change', function(jQEvent) {
var $checkbox = $(jQEvent.target);
manageCheckbox($checkbox);
var comboFilter = getComboFilter(filters);
/*var searchResult = qsRegex ? $(this).text().match(qsRegex) : true;
var filterResult = function() {
return comboFilter && searchResult;
}*/
$grid.isotope({
filter: comboFilter //or filterResult
});
});
});
function getComboFilter(filters) {
var i = 0;
var comboFilters = [];
var message = [];
for (var prop in filters) {
message.push(filters[prop].join(' '));
var filterGroup = filters[prop];
// skip to next filter group if it doesn't have any values
if (!filterGroup.length) {
continue;
}
if (i === 0) {
// copy to new array
comboFilters = filterGroup.slice(0);
} else {
var filterSelectors = [];
// copy to fresh array
var groupCombo = comboFilters.slice(0); // [ A, B ]
// merge filter Groups
for (var k = 0, len3 = filterGroup.length; k < len3; k++) {
for (var j = 0, len2 = groupCombo.length; j < len2; j++) {
filterSelectors.push(groupCombo[j] + filterGroup[k]); // [ 1, 2 ]
}
}
// apply filter selectors to combo filters for next group
comboFilters = filterSelectors;
}
i++;
}
var comboFilter = comboFilters.join(', ');
return comboFilter;
}
// use value of search field to filter
var $quicksearch = $('.quicksearch').keyup(debounce(function() {
qsRegex = new RegExp($quicksearch.val(), 'gi');
$grid.isotope();
}, ));
// debounce so filtering doesn't happen every millisecond
function debounce(fn, threshold) {
var timeout;
threshold = threshold || 100;
return function debounced() {
clearTimeout(timeout);
var args = arguments;
var _this = this;
function delayed() {
fn.apply(_this, args);
}
timeout = setTimeout(delayed, threshold);
}
}
function manageCheckbox($checkbox) {
var checkbox = $checkbox[0];
var group = $checkbox.parents('.option-set').attr('data-group');
// create array for filter group, if not there yet
var filterGroup = filters[group];
if (!filterGroup) {
filterGroup = filters[group] = [];
}
var isAll = $checkbox.hasClass('all');
// reset filter group if the all box was checked
if (isAll) {
delete filters[group];
if (!checkbox.checked) {
checkbox.checked = 'checked';
}
}
// index of
var index = $.inArray(checkbox.value, filterGroup);
if (checkbox.checked) {
var selector = isAll ? 'input' : 'input.all';
$checkbox.siblings(selector).prop('checked', false);
if (!isAll && index === -1) {
// add filter to group
filters[group].push(checkbox.value);
}
} else if (!isAll) {
// remove filter from group
filters[group].splice(index, 1);
// if unchecked the last box, check the all
if (!$checkbox.siblings('[checked]').length) {
$checkbox.parents('.option-set').find(selector).prop('checked', false);
}
}
I found the solution by myself, but i had to add a second function for returning the searchresult. Otherwise the search function is triggered only after using a checkbox or leaving the search box input field.
How could i avoid this redundand code?
JS:
// use value of search field to filter
var $quicksearch = $('.quicksearch').keyup(debounce(function() {
qsRegex = new RegExp($quicksearch.val(), 'gi');
$grid.isotope();
}, 200));
$(function() {
$grid = $('#grid');
$grid.isotope({
filter: function() {
var searchResult = qsRegex ? $(this).text().match(qsRegex) : true;
return searchResult;
}
});
// do stuff when checkbox change
$('#options').on('change', function(jQEvent) {
var $checkbox = $(jQEvent.target);
manageCheckbox($checkbox);
var comboFilter = getComboFilter(filters);
$grid.isotope({
filter: function() {
var buttonResult = comboFilter ? $(this).is(comboFilter) : true;
var searchResult = qsRegex ? $(this).text().match(qsRegex) : true;
return buttonResult && searchResult;
}
});
});
});

Make Fivestar 7.x-2.2 mobile-friendly

I am using the Fivestar 2.2 module. Everything works fine, but voting on a touch screen doesn't: It is impossible to give 5 stars on a 5 star widget, even though it works perfectly on the desktop. Unfortunately I'm not allowed to provide a link.
Is there someone who already solved this? Drupal.org is not a help.
/**
* #file
*
* Fivestar JavaScript behaviors integration.
*/
/**
* Create a degradeable star rating interface out of a simple form structure.
*
* Originally based on the Star Rating jQuery plugin by Wil Stuckey:
* http://sandbox.wilstuckey.com/jquery-ratings/
*/
(function($){ // Create local scope.
Drupal.behaviors.fivestar = {
attach: function (context) {
$(context).find('div.fivestar-form-item').once('fivestar', function() {
var $this = $(this);
var $container = $('<div class="fivestar-widget clearfix"></div>');
var $select = $('select', $this);
// Setup the cancel button
var $cancel = $('option[value="0"]', $this);
if ($cancel.length) {
$('<div class="cancel">' + $cancel.text() + '</div>')
.appendTo($container);
}
// Setup the rating buttons
var $options = $('option', $this).not('[value="-"], [value="0"]');
var index = -1;
$options.each(function(i, element) {
var classes = 'star-' + (i+1);
classes += (i + 1) % 2 == 0 ? ' even' : ' odd';
classes += i == 0 ? ' star-first' : '';
classes += i + 1 == $options.length ? ' star-last' : '';
$('<div class="star">' + element.text + '</div>')
.addClass(classes)
.appendTo($container);
if (element.value == $select.val()) {
index = i + 1;
}
});
if (index != -1) {
$container.find('.star').slice(0, index).addClass('on');
}
$container.addClass('fivestar-widget-' + ($options.length));
$container.find('a')
.bind('click', $this, Drupal.behaviors.fivestar.rate)
.bind('mouseover', $this, Drupal.behaviors.fivestar.hover);
$container.bind('mouseover mouseout', $this, Drupal.behaviors.fivestar.hover);
// Attach the new widget and hide the existing widget.
$select.after($container).css('display', 'none');
// Allow other modules to modify the widget.
Drupal.attachBehaviors($this);
});
},
rate: function(event) {
var $this = $(this);
var $widget = event.data;
var value = this.hash.replace('#', '');
$('select', $widget).val(value).change();
var $this_star = (value == 0) ? $this.parent().parent().find('.star') :
$this.closest('.star');
$this_star.prevAll('.star').andSelf().addClass('on');
$this_star.nextAll('.star').removeClass('on');
if(value==0){
$this_star.removeClass('on');
}
event.preventDefault();
},
hover: function(event) {
var $this = $(this);
var $widget = event.data;
var $target = $(event.target);
var $stars = $('.star', $this);
if (event.type == 'mouseover') {
var index = $stars.index($target.parent());
$stars.each(function(i, element) {
if (i <= index) {
$(element).addClass('hover');
} else {
$(element).removeClass('hover');
}
});
} else {
$stars.removeClass('hover');
}
}
};
})(jQuery);
Sorry if it's not what you asked but I'll try to help. Don't use fivestar, I've been in the same situation. I suggest you to try the rate module (https://www.drupal.org/project/rate) which is in my opinion a more complete solution.
I have a responsive website which of course works with mobile devices and you can vote without problem, although I can't assure it was mobile ready.

how to custom sort an array based on its status followed by another field?

So I have an array, I need to sort it based on status in the following order i.e. failure->warn->completed.
Normally, I use lodash for sorting but its a bit of complex order here. It also needs to sort according to run after sorting with run. Im not sure how to start on this.
var arr = [{"status":"failure","name":"one","run":1},
{"status":"failure","name":"two","run":2},
{"status":"warn","name":"three","run":1},
{"status":"warn","name":"four","run":2},
{"status":"completed","name":"five","run":1}]
something like this?
Add a extra property for your sort key.
var arrnew = arr.map(function(item){
switch(item.status){
case "failure":
item.statusId=1;
break;
case "warn":
item.statusId=2;}
//...
return item} );
Sort by using that
_.sortBy(arrnew, 'statusId');
Sorts based on "status", and then the sub-slices by "run" 1 or 2:
let status_vals = [ "failure", "warn", "completed" ];
let arr = [
{"status":"failure","name":"one","run":1},
{"status":"failure","name":"two","run":2},
{"status":"warn","name":"three","run":1},
{"status":"warn","name":"four","run":2},
{"status":"completed","name":"five","run":1}
];
function sortIt ( status_arr, sort_arr ) {
let sorted_arr = [];
status_arr.forEach ( d => {
let temp = arr.filter ( obj => {
return obj.status === d;
} );
var length = temp.length;
for ( var i = 0; i < length; i++ ) {
if ( temp [ 0 ].run > temp [ i ].run ) {
temp.push ( temp.shift ( ) );
}
}
sorted_arr = [ ...sorted_arr, ...temp ];
} );
return sorted_arr;
}
sortIt ( status_vals, arr );

NgTable using API and groupBy with a global filter

I'm having difficulty with NgTable, however the functionality I'm looking for may be a limitation on the table framework.
I'm using an API call within the getData, and the data is being grouped (via the groupBy property in the settings param).
I want to be able to use a global filter on the data, I can't seem to get it work with grouping. There's two examples, except they don't mix:
Grouping: http://ng-table.com/#/grouping/demo-grouping-basic
Global filtering: http://ng-table.com/#/filtering/demo-api
Any suggestions?
Table declaration/config
$scope.tableNotesParams = new ngTableParams({
page: 1, // show first page
count: 10, // count per page: use total result set in this case,
sorting: {
created_at: 'desc'
}
}, {
groupBy: function( note ) {
return moment( note.created_at ).format( 'YYYY' );
},
getData: function ( $defer, params ) {
$scope.request.notes.state = 'started';
$scope.request.notes.notesSpinner = true;
var offset = params.count() * ( params.page() - 1 );
// Default
var urlQueryParams = {
'email': member.accounts.email,
'offset': offset,
'limit': params.count() || 10
};
notesApiService.getNotes( urlQueryParams ).then( function ( results ) {
$scope.notes = results.data;
$scope.noteMembers = extractionService.getAllUniqueMembers( $scope.notes );
// Get the range values, expecting value to be: items 1-10/655
var noteHeaders = results.headers();
var notesRangeValues = noteHeaders['content-range'].match( /(\d{1,})/g );
$scope.tableNotesMetaData = {
offsetStart: notesRangeValues[0] || 0,
offsetEnd : notesRangeValues[1] || 0,
totalCount : notesRangeValues[2] || 0
};
// Update parent controller count
$scope.tabs.notes.count = notesRangeValues[2] || 0;
// Update the total
params.total( $scope.tableNotesMetaData.totalCount );
var orderedData = params.sorting() ?
$filter('orderBy')($scope.notes, params.orderBy()) :
$scope.notes;
$defer.resolve( orderedData );
$scope.request.notes.state = 'completed';
$scope.request.notes.notesSpinner = false;
});
}
});
Edit:
The filtering example for a global filter doesn't do anything to the grouped data:
function applyGlobalSearch(){
var term = self.globalSearchTerm;
if (self.isInvertedSearch){
term = "!" + term;
}
self.tableParams.filter({ $: term });
}
I don't think it's performant to query your notesApiService.getNotes() in the getData()-function, but whatever. Since we don't have the HTML or a JSBin to work with, it's mostly guestimate:
notesApiService.getNotes( urlQueryParams ).then( function ( results ) {
var term = $scope.globalSearchTerm.toLowerCase();
if (term.length == 0) {
$scope.notes = angular.copy(results.data, []);
} else if (term.length > 1) {
$scope.notes = results.data.filter(function(item) {
var val = JSON.stringify(item).toLowerCase();
return (val.indexOf(term) != -1);
});
}

Delete multiple items from grid using CheckboxSelectionModel

Using ExtJs4.1 on Sencha Architect.
I have following code in my onDeleteButton code
onDeleteButtonClick: function(button, e, options) {
var active = this.activeRecord;
var myGrid = Ext.getCmp('publisherResultsGridView'),
sm = myGrid.getSelectionModel(),
selection = sm.getSelection(); // gives you a array of records(models)
if (selection.length > 0){
for( var i = 0; i < selection.length; i++) {
this.application.log('OnDeleteItemID is ' + selection);
}
this.remove(selection);
}
Code for Remove Function
remove: function(record) {
var store = Ext.getStore('PublisherProperties');
store.proxy.url = MasterDataManager.globals.url + "Publishers/";
store.remove(record);
store.sync();
When I run it, I could see an array of objects in my log, also I dont get any errors after the remove function is executed. But the store doesnt update, I mean it doesnt remove the selected items.
Can somebody please help me.
Thanks
I solved my problem by making the following changes.
To onDeleteButtonClick
if (selection.length > 0){
for( var i = 0; i < selection.length; i++) {
this.application.log('OnDeleteItemID is ' + selection[i].data.id);
this.remove(selection[i]);
}
}
To Remove function
remove: function(record) {
var store = Ext.getStore('PublisherProperties');
this.application.log('Remove Function is ' + record);
store.proxy.url = MasterDataManager.globals.url + "Publishers/" + record.data.id;
store.load({
scope : this,
callback : function(records, operation, success){
if (records.length > 0){
var store2 = Ext.getStore('PublisherProperties');
store2.proxy.url = MasterDataManager.globals.url + "Publishers/";
store2.remove(records[0]);
store2.sync();
}
}
});
//store.remove(record);
//store.sync();

Resources