How to reorder kendo grid rows? - javascript

I am dynamically adding rows to kendo gid. Now i need a reorder button ,where i can able to move a row up and down . i don't want drag and drop functionality. Im able to get each row id .need some help...
<script>
$(document).ready(function () {
var grid = $("#grid").kendoGrid({
columns: [
{ field: "Control", title: "Web Control Name" },
{ field: "Value", title: "Drag & Drop Variable" },
{
command: [
{ title: "create", template: "<img class='ob-image' src='../DefaultAssets/Images/New.png' style='padding: 0 15px 0 5px;' />" },
{ title: "reorder", template: "<img class ='up-image' src='../DefaultAssets/Images/Upimages.jpg' style='padding: 0 15px 0 5px;' />" },
{ "name": "destroy", title: "" }
],
},
],
dataSource: {
data: [
{
Control: "Web Control name",
Value: "Drag & Drop Variable"
},
],
schema: {
model: {
Control: "Web Control name",
Value: "Drag & Drop Variable"
}
}
},
reorderable: true,
editable: {
// confirmation: "Are you sure that you want to delete this record?",
createAt: "bottom"
},
remove: function (e) {
}
});
var grid = $("#grid").data("kendoGrid");
$("#grid").on("click", ".ob-image", function () {
var grid = $("#grid").data("kendoGrid");
grid.addRow();
});
$("#grid").on("click", ".up-image", function () {
var row = $(this).closest("tr");
var rowIdx = $("tr", grid.tbody).index(row);
alert(rowIdx);
});
});

You can create a template column and use the data source insert and remove methods to rearrange the data items. The grid will be refreshed automatically.
$("#grid").kendoGrid({
dataSource: [
{ foo: "foo" },
{ foo: "bar" },
{ foo: "baz" }
],
columns: [
{ field: "foo" },
{ template: '<button onclick="return up(\'#=uid#\')">up</button><button onclick="return down(\'#=uid#\')">down</button>' }
]
});
function up(uid) {
var grid = $("#grid").data("kendoGrid");
var dataItem = grid.dataSource.getByUid(uid);
var index = grid.dataSource.indexOf(dataItem);
var newIndex = Math.max(0, index - 1);
if (newIndex != index) {
grid.dataSource.remove(dataItem);
grid.dataSource.insert(newIndex, dataItem);
}
return false;
}
function down(uid) {
var grid = $("#grid").data("kendoGrid");
var dataItem = grid.dataSource.getByUid(uid);
var index = grid.dataSource.indexOf(dataItem);
var newIndex = Math.min(grid.dataSource.total() - 1, index + 1);
if (newIndex != index) {
grid.dataSource.remove(dataItem);
grid.dataSource.insert(newIndex, dataItem);
}
return false;
}
Here is a live demo: http://jsbin.com/ExOgiPib/1/edit

Once upon a time I was a Kendo UI user. I had a problem with sorting as well and this is how I solved it back then (after a lot of suffering):
//Sort Hack
/*
Changes all dataSources to case insensitive sorting (client side sorting).
This snipped enable case insensitive sorting on Kendo UI grid, too.
The original case sensitive comparer is a private and can't be accessed without modifying the original source code.
tested with Kendo UI version 2012.2.710 (Q2 2012 / July 2012).
*/
var CaseInsensitiveComparer = {
getterCache: {},
getter: function (expression) {
return this.getterCache[expression] = this.getterCache[expression] || new Function("d", "return " + kendo.expr(expression));
},
selector: function (field) {
return jQuery.isFunction(field) ? field : this.getter(field);
},
asc: function (field) {
var selector = this.selector(field);
return function (a, b) {
if ((selector(a).toLowerCase) && (selector(b).toLowerCase)) {
a = selector(a).toLowerCase(); // the magical part
b = selector(b).toLowerCase();
}
return a > b ? 1 : (a < b ? -1 : 0);
};
},
desc: function (field) {
var selector = this.selector(field);
return function (a, b) {
if ((selector(a).toLowerCase) && (selector(b).toLowerCase)) {
a = selector(a).toLowerCase(); // the magical part
b = selector(b).toLowerCase();
}
return a < b ? 1 : (a > b ? -1 : 0);
};
},
create: function (descriptor) {
return this[descriptor.dir.toLowerCase()](descriptor.field);
},
combine: function (comparers) {
return function (a, b) {
var result = comparers[0](a, b),
idx,
length;
for (idx = 1, length = comparers.length; idx < length; idx++) {
result = result || comparers[idx](a, b);
}
return result;
};
}
};
kendo.data.Query.prototype.normalizeSort = function (field, dir) {
if (field) {
var descriptor = typeof field === "string" ? { field: field, dir: dir} : field,
descriptors = jQuery.isArray(descriptor) ? descriptor : (descriptor !== undefined ? [descriptor] : []);
return jQuery.grep(descriptors, function (d) { return !!d.dir; });
}
};
kendo.data.Query.prototype.sort = function (field, dir, comparer) {
var idx,
length,
descriptors = this.normalizeSort(field, dir),
comparers = [];
comparer = comparer || CaseInsensitiveComparer;
if (descriptors.length) {
for (idx = 0, length = descriptors.length; idx < length; idx++) {
comparers.push(comparer.create(descriptors[idx]));
}
return this.orderBy({ compare: comparer.combine(comparers) });
}
return this;
};
kendo.data.Query.prototype.orderBy = function (selector) {
var result = this.data.slice(0),
comparer = jQuery.isFunction(selector) || !selector ? CaseInsensitiveComparer.asc(selector) : selector.compare;
return new kendo.data.Query(result.sort(comparer));
};
kendo.data.Query.prototype.orderByDescending = function (selector) {
return new kendo.data.Query(this.data.slice(0).sort(CaseInsensitiveComparer.desc(selector)));
};
//Sort Hack
You can implement your own solution, you can add your own functions and the order change will happen as you want.

Related

javascript: Alter the output of a function to the specified decimal place

I am not very good with my javascript but recently needed to work with a library to output an aggregated table. Was using fin-hypergrid.
There was a part where I need to insert a sum function (rollups.sum(11) in this example)to an object so that it can compute an aggregated value in a table like so:
aggregates = {Value: rollups.sum(11)}
I would like to change this value to return 2 decimal places and tried:
rollups.sum(11).toFixed(2)
However, it gives the error : "rollups.sum(...).toFixed is not a function"
If I try something like:
parseFloat(rollups.sum(11)).toFixed(2)
it throws the error: "can't assign to properties of (new String("NaN")): not an object"
so it has to be a function object.
May I know if there is a way to alter the function rollups.sum(11) to return a function object with 2 decimal places?
(side info: rollups.sum(11) comes from a module which gives:
sum: function(columnIndex) {
return sum.bind(this, columnIndex);
}
)
Sorry I could not post sample output here due to data confidentiality issues.
However, here is the code from the example I follow. I basically need to change rollups.whatever to give decimal places. The "11" in sum(11) here refers to a "column index".
window.onload = function() {
var Hypergrid = fin.Hypergrid;
var drillDown = Hypergrid.drillDown;
var TreeView = Hypergrid.TreeView;
var GroupView = Hypergrid.GroupView;
var AggView = Hypergrid.AggregationsView;
// List of properties to show as checkboxes in this demo's "dashboard"
var toggleProps = [{
label: 'Grouping',
ctrls: [
{ name: 'treeview', checked: false, setter: toggleTreeview },
{ name: 'aggregates', checked: false, setter: toggleAggregates },
{ name: 'grouping', checked: false, setter: toggleGrouping}
]
}
];
function derivedPeopleSchema(columns) {
// create a hierarchical schema organized by alias
var factory = new Hypergrid.ColumnSchemaFactory(columns);
factory.organize(/^(one|two|three|four|five|six|seven|eight)/i, { key: 'alias' });
var columnSchema = factory.lookup('last_name');
if (columnSchema) {
columnSchema.defaultOp = 'IN';
}
//factory.lookup('birthState').opMenu = ['>', '<'];
return factory.schema;
}
var customSchema = [
{ name: 'last_name', type: 'number', opMenu: ['=', '<', '>'], opMustBeInMenu: true },
{ name: 'total_number_of_pets_owned', type: 'number' },
{ name: 'height', type: 'number' },
'birthDate',
'birthState',
'employed',
{ name: 'income', type: 'number' },
{ name: 'travel', type: 'number' }
];
var peopleSchema = customSchema; // or try setting to derivedPeopleSchema
var gridOptions = {
data: people1,
schema: peopleSchema,
margin: { bottom: '17px' }
},
grid = window.g = new Hypergrid('div#json-example', gridOptions),
behavior = window.b = grid.behavior,
dataModel = window.m = behavior.dataModel,
idx = behavior.columnEnum;
console.log('Fields:'); console.dir(behavior.dataModel.getFields());
console.log('Headers:'); console.dir(behavior.dataModel.getHeaders());
console.log('Indexes:'); console.dir(idx);
var treeView, dataset;
function setData(data, options) {
options = options || {};
if (data === people1 || data === people2) {
options.schema = peopleSchema;
}
dataset = data;
behavior.setData(data, options);
idx = behavior.columnEnum;
}
// Preset a default dialog options object. Used by call to toggleDialog('ColumnPicker') from features/ColumnPicker.js and by toggleDialog() defined herein.
grid.setDialogOptions({
//container: document.getElementById('dialog-container'),
settings: false
});
// add a column filter subexpression containing a single condition purely for demo purposes
if (false) { // eslint-disable-line no-constant-condition
grid.getGlobalFilter().columnFilters.add({
children: [{
column: 'total_number_of_pets_owned',
operator: '=',
operand: '3'
}],
type: 'columnFilter'
});
}
window.vent = false;
//functions for showing the grouping/rollup capabilities
var rollups = window.fin.Hypergrid.analytics.util.aggregations,
aggregates = {
totalPets: rollups.sum(2),
averagePets: rollups.avg(2),
maxPets: rollups.max(2),
minPets: rollups.min(2),
firstPet: rollups.first(2),
lastPet: rollups.last(2),
stdDevPets: rollups.stddev(2)
},
groups = [idx.BIRTH_STATE, idx.LAST_NAME, idx.FIRST_NAME];
var aggView, aggViewOn = false, doAggregates = false;
function toggleAggregates() {
if (!aggView){
aggView = new AggView(grid, {});
aggView.setPipeline({ includeSorter: true, includeFilter: true });
}
if (this.checked) {
grid.setAggregateGroups(aggregates, groups);
aggViewOn = true;
} else {
grid.setAggregateGroups([], []);
aggViewOn = false;
}
}
function toggleTreeview() {
if (this.checked) {
treeView = new TreeView(grid, { treeColumn: 'State' });
treeView.setPipeline({ includeSorter: true, includeFilter: true });
treeView.setRelation(true, true);
} else {
treeView.setRelation(false);
treeView = undefined;
delete dataModel.pipeline; // restore original (shared) pipeline
behavior.setData(); // reset with original pipeline
}
}
var groupView, groupViewOn = false;
function toggleGrouping(){
if (!groupView){
groupView = new GroupView(grid, {});
groupView.setPipeline({ includeSorter: true, includeFilter: true });
}
if (this.checked){
grid.setGroups(groups);
groupViewOn = true;
} else {
grid.setGroups([]);
groupViewOn = false;
}
}
you may try:
(rollups.sum(11)).toFixed(2)
enclosing number in parentheses seems to make browser bypass the limit that identifier cannot start immediately after numeric literal
edited #2:
//all formatting and rendering per cell can be overridden in here
dataModel.getCell = function(config, rendererName) {
if(aggViewOn)
{
if(config.columnName == "total_pets")
{
if(typeof(config.value) == 'number')
{
config.value = config.value.toFixed(2);
}
else if(config.value && config.value.length == 3 && typeof(config.value[1]) == 'number')
{
config.value = config.value[1].toFixed(2);
}
}
}
return grid.cellRenderers.get(rendererName);
};

Why the gridApi.on.edit.beginCellEdit in angular-ui-grid cannot update the new drop-down options immeidiately?

I have the same problem with this one Why ui grid value drop-down box will be assigned in the event fires before beginCellEdit in angular
And have little bit difference. After I updated the editDropdownOptionArray it still keep the old value, It's only have the new value in the next click.
Hope everyone can help me with this one.
Thank you.
Here is my code snippet:
The html of the dropdown:
<div>
<form name="inputForm">
<select ng-class="'colt' + col.uid"
ui-grid-edit-dropdown
ng-model="MODEL_COL_FIELD"
ng-options="field CUSTOM_FILTERS for field in editDropdownOptionsArray"></select>
</form>
</div>
The controller code:
$scope.menuColumns = [
{ displayName: 'Menu', field: 'name', enableCellEdit: false },
{
displayName: 'Access Level', field: 'accessLevelName',
editableCellTemplate: 'Scripts/application/role/directive/dropdown-menu-assignment.html',
editDropdownValueLabel: 'Access Level', editDropdownOptionsArray: userMgtConstant.menuAccessLevel
}
];
$scope.menuOptions = {
data: [],
onRegisterApi: function (gridApi) {
gridApi.edit.on.beginCellEdit($scope, function (rowEntity, colDef, event) {
if (rowEntity.parent === true) {
colDef.editDropdownOptionsArray = $scope.levelList;
} else {
colDef.editDropdownOptionsArray = $scope.childLevelList;
}
});
gridApi.edit.on.afterCellEdit($scope, function (rowEntity, colDef, newValue, oldValue) {
if (rowEntity.parent !== true) {
if(rowEntity.name === 'Revenue Bench'){
var accessLevel = commonUtils.getIdFromName(rowEntity.accessLevelName, userMgtConstant.menuAccessLevel);
if(accessLevel > 1){
$scope.isShowFunctionAssignment = false;
} else if(rowEntity.functionAssignments.length !== 0) {
$scope.isShowFunctionAssignment = true;
}
}
} else {
// udpate child dropdown list menu
var index = _(userMgtConstant.menuAccessLevel).indexOf(newValue);
$scope.childLevelList = $scope.levelList.filter(function (item, i) {
return i >= index;
});
if($scope.childLevelList.length > 2){
parentSwitch = true;
}
if($scope.childLevelList.length < 3 && parentSwitch){
colDef.editDropdownOptionsArray = $scope.childLevelList;
parentSwitch = false;
}
// update all child value
_($scope.menuOptions.data).each(function (dataItem) {
if (dataItem.parent !== true) { // prevent infinite loop
dataItem.accessLevelName = newValue;
}
});
}
});
}
};
Here is the usage of the grid:
<inline-edit-grid options="menuOptions" columns="menuColumns"></inline-edit-grid>
You should look into the usage of editDropdownRowEntityOptionsArrayPath instead of editDropdownOptionsArray
From the docs :
editDropdownRowEntityOptionsArrayPath can be used as an alternative to
editDropdownOptionsArray when the contents of the dropdown depend on
the entity backing the row.
Here is a link to tutorial

getting datatables error, can't figure out why : TypeError: d[i] is undefined & TypeError: b.nTableWrapper is null

We use jQuery DataTables plug in across our app and it works pretty well. However we're encountering an error when we try load up the plug in with mock data (services aren't ready yet) in a modal on the page. We get the following errors ( the 2nd one happens after you click the link again to open the modal)
TypeError: d[i] is undefined
TypeError: b.nTableWrapper is null
The code looks correct, so I can't figure it out. Anyone with experience on this error ? We built the table map to correspond with the sample data nodes - and we've also tried maps with current working ones to no avail. (They are separated by purpose).
I've added the HTML in the fiddle. But basically it's just a simple table with the ID - the other datatables across the site work just fine with the same structure. Just stumped.
var sampleData = [{
"approvable": true,
"id": 4938,
"order_number": "3948948392893",
"order_template": "AJHSFJKHAS-SDJAS",
"size": "45mb",
"size_sort": 4500,
"ad_type": "testadtype",
"production_status": "yep!"
}
];
var makeCampaignApproveModal = function () {
var $approveParams;
var $approveComments = $('#approveComments');
var $approveCampaignForm = $('#approveCampaignForm');
var $campaignApprove = $('#campaignApprove');
var $approveCampaignHeader = $campaignApprove.children('h3');
var $ratingStars = $('#ratingStars');
var $ratingStar = $('.ratingStar');
var $ratingApproveCampaign = $('#ratingApproveCampaign');
var $ratingCancelCampaign = $('#ratingCancelCampaign');
var init = function () {
makeCampaignBulkOrders(sampleData);
//bindings
$ratingStar.mouseover(function (e) {
var $this = $(this);
$this.prevAll().addClass('active');
$this.nextAll().addClass('inactive');
});
$ratingStar.mouseout(function (e) {
var $this = $(this);
$this.prevAll().removeClass('active');
$this.nextAll().removeClass('inactive');
});
$ratingStar.on("click", function (e) {
e.preventDefault();
var $this = $(this);
//style prevs
$this.addClass('selected');
$this.prevAll().addClass('selected');
$this.nextAll().removeClass('selected');
$ratingStars.data('rating', $this.attr('rel'));
});
$ratingApproveCampaign.on("click", function (e) {
e.preventDefault();
var approveHandler = Portal.Details.synchronousRatingHandler;
utils.makeProxyCall((actionQueryPath + '/proof/approve'), approveHandler, Portal.Details.proofReturnE);
callInProgress();
return false;
});
$ratingCancelCampaign.on("click", function (e) {
e.preventDefault();
$campaignApprove.modality('close');
});
$campaignApprove.addClass('initted');
}; //init
if (!$campaignApprove.hasClass('initted')) {
init();
}
aep.utils.setupForm($approveCampaignForm, true, false);
$ratingStars.data();
$ratingApproveCampaign.text($l(2019));
$approveCampaignHeader.html($l(2018) + '<span class="actionModalObjectNumber"></span>');
updateModalHeader($campaignApprove);
var curRating = actionDetails['rating'];
$ratingStar.each(function () {
var $this = $(this);
if ($this.attr('rel') <= curRating) {
$this.addClass('selected');
} else {
$this.removeClass('selected');
}
});
$ratingStars.data('rating', curRating);
$campaignApprove.modality(modalConfig);
};
var makeCampaignBulkOrders = function (coData) {
var $campaignBulkOrders = $('#campaignBulkOrders');
var $campaignBulkOrdersTable = $('#bulk-ords-table');
var DTConfig = {
'bDestroy': true,
'bAutoWidth': true,
'iDisplayLength': -1,
'bPaginate': false,
'sScrollY': '200px',
'bScrollCollapse': true,
'oLanguage': {
'sSearch': $l(1024)
}
};
var coData = sampleData || [];
var coMap = getTableMapBulkOrders();
var cDTConfig = DTConfig;
cDTConfig['aaData'] = coData;
cDTConfig['aaColumns'] = coMap;
cDTConfig['aaSorting'] = [[1, 'desc']];
cDTConfig['sScrollY'] = '';
cDTConfig['bScrollCollapse'] = false;
$campaignBulkOrders.find('.tableLoading').hide();
$campaignBulkOrdersTable.dataTable(cDTConfig).fnDraw();
cDTConfig['aaSorting'] = [];
};
var getTableMapBulkOrders = function () {
return [{
oid: 'approvable',
'sTitle': '',
'mDataProp': function (source, type, val) {
if (type == "display") {
return '<input type="checkbox" class="campaign-order-approval" rel="' + source.id + '" />';
}
return source.id;
},
'sClass': 'checkbox'
},
{
oid: 'order_number',
'sClass': 'order_number',
'mDataProp': function (source, type, val) {
var ordNumber = '<a class="detailsLink" href="/portal/details/#orders/' + source.id + '">' + source.order_number + '</a>';
if (type == 'display') {
return ordNumber;
}
return source['order_number'];
},
'sTitle': $l(2089),
'sClass': 'orderNumber'
},
{
oid: 'order_template',
'mDataProp': 'order_template',
'sTitle': $l(2048),
'sClass': 'order_template'
}, {
oid: 'fileSize',
'mDataProp': function (source, type, val) {
if (type == "sort") {
return source['size_sort'];
}
return source['size'];
},
'sTitle': $l(2099),
"sType": "numeric",
'sClass': 'file_size'
},
{
oid: 'ad_type',
'mDataProp': 'ad_type',
'sTitle': $l(2045),
'sClass': 'ad_type'
}, {
oid: 'production_status',
'mDataProp': 'production_status',
'sTitle': $l(2097),
'sClass': 'production_status'
}
];
};
jsfiddle is over here

Angular ui grid, change behavior of "Export all data as csv"

I have a uigrid that contains a large number of column definitions that aren't initially filled with data because the data set would be too large. Instead, I get the requested column data when the column visibility changes.
This causes an issue with the built in csv exporter. When someone chooses to "Export all data as csv" they get numerous empty columns.
What I would like to do it change the default behavior of the built in csv menu items to use uiGridExporterConstants.VISIBLE.
I was going to roll my own menu items like so:
$scope.gridOptions.exporterMenuCsv = false; //Rolling our own menu items to exclude invisible columns
$scope.gridOptions.gridMenuCustomItems = [
{
title: 'Export All to CSV',
action: function ($event) {
var myElement = angular.element(document.querySelectorAll(".custom-csv-link-location"));
$scope.gridApi.exporter.csvExport( uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, myElement );
}
},{
title: 'Export Selected to CSV',
action: function ($event) {
var myElement = angular.element(document.querySelectorAll(".custom-csv-link-location"));
$scope.gridApi.exporter.csvExport( uiGridExporterConstants.SELECTED, uiGridExporterConstants.VISIBLE, myElement );
}
},{
title: 'Export Visible to CSV',
action: function ($event) {
var myElement = angular.element(document.querySelectorAll(".custom-csv-link-location"));
$scope.gridApi.exporter.csvExport( uiGridExporterConstants.VISIBLE, uiGridExporterConstants.VISIBLE, myElement );
}
}
];
But only the first item appears. Maybe I have to use addToGridMenu, but I'm not sure. Ideally, I'd like to leave the default items in place, but just have "export all data as csv" only export the visible columns.
I ended up having to use gridApi.core.addToGridMenu like so:
$scope.gridOptions = {
exporterCsvLinkElement: angular.element(document.querySelectorAll('.custom-csv-link-location')),
onRegisterApi: function(gridApi){
$scope.gridApi = gridApi;
$interval(function () {
gridApi.core.addToGridMenu(gridApi.grid, [{
title: 'Export All to CSV',
order: 1,
action: function ($event) {
var myElement = angular.element(document.querySelectorAll(".custom-csv-link-location"));
$scope.gridApi.exporter.csvExport(uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE, myElement);
}
}]);
gridApi.core.addToGridMenu(gridApi.grid, [{
title: 'Export Visible to CSV',
order: 2,
action: function ($event) {
var myElement = angular.element(document.querySelectorAll(".custom-csv-link-location"));
$scope.gridApi.exporter.csvExport(uiGridExporterConstants.VISIBLE, uiGridExporterConstants.VISIBLE, myElement);
}
}]);
}, 0, 1);
$scope.gridApi.selection.on.rowSelectionChanged($scope, function () { //for single row selection
if (gridApi.grid.selection.selectedCount > 0 && !selectionMenuAdded) { //only add menu item if something is selected and if the menu item doesn't already exist
selectionMenuAdded = true;
gridApi.core.addToGridMenu(gridApi.grid, [{
title: 'Export Selected to CSV',
order: 3,
id: 'uiSel',
action: function ($event) {
if (gridApi.grid.selection.selectedCount > 0) {
var uiExporter = uiGridExporterService;
var grid = $scope.gridApi.grid;
uiExporter.loadAllDataIfNeeded(grid, uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE).then(function () {
var exportColumnHeaders = uiExporter.getColumnHeaders(grid, uiGridExporterConstants.VISIBLE);
var selectionData = [];
gridApi.selection.getSelectedRows().forEach(function (entry) {
var innerData = [];
for (var e in entry) { //create the inner data object array
if (e !== '$$hashKey') {
var selectObj = { value: entry[e] };
innerData.push(selectObj);
}
}
selectionData.push(innerData); //push the inner object value array to the larger array as required by formatAsCsv
});
var csvContent = uiExporter.formatAsCsv(exportColumnHeaders, selectionData, grid.options.exporterCsvColumnSeparator);
uiExporter.downloadFile($scope.gridOptions.exporterCsvFilename, csvContent, grid.options.exporterOlderExcelCompatibility);
});
}
}
}]);
} else if (gridApi.grid.selection.selectedCount === 0 && selectionMenuAdded) {
selectionMenuAdded = false;
gridApi.core.removeFromGridMenu(gridApi.grid, 'uiSel');
}
});
$scope.gridApi.selection.on.rowSelectionChangedBatch($scope, function () {
if (gridApi.grid.selection.selectedCount > 0 && !selectionMenuAdded) {
selectionMenuAdded = true;
gridApi.core.addToGridMenu(gridApi.grid, [{
title: 'Export Selected to CSV',
order: 3,
id: 'uiSel',
action: function ($event) {
if (gridApi.grid.selection.selectedCount > 0) {
var uiExporter = uiGridExporterService;
var grid = $scope.gridApi.grid;
uiExporter.loadAllDataIfNeeded(grid, uiGridExporterConstants.ALL, uiGridExporterConstants.VISIBLE).then(function () {
var exportColumnHeaders = uiExporter.getColumnHeaders(grid, uiGridExporterConstants.VISIBLE);
var selectionData = [];
gridApi.selection.getSelectedRows().forEach(function (entry) {
var innerData = [];
for (var e in entry) {
if (e !== '$$hashKey') {
var selectObj = { value: entry[e] };
innerData.push(selectObj);
}
}
selectionData.push(innerData);
});
var csvContent = uiExporter.formatAsCsv(exportColumnHeaders, selectionData, grid.options.exporterCsvColumnSeparator);
uiExporter.downloadFile($scope.gridOptions.exporterCsvFilename, csvContent, grid.options.exporterOlderExcelCompatibility);
});
}
}
}]);
} else if (gridApi.grid.selection.selectedCount === 0 && selectionMenuAdded) {
selectionMenuAdded = false;
gridApi.core.removeFromGridMenu(gridApi.grid, 'uiSel');
}
});
}
}
Be sure to inject uiGridExporterConstants and uiGridExporterService.

Disable header in a column and keep sorting with JQUERY

I'm working with a table and I need that the header of a particular column be disable but this column need to be sorted by JQUERY, do somebody knows how do I have to do it?
Here is the jQuery code:
function TaskSortingAndFiltering() {
var taskTable = $("#TaskTable");
if (taskTable != null && taskTable.attr('rows') != undefined) {
// If exists at least one Task, set the paging and sorting to the table
if (taskTable.attr('rows').length > 1) {
$("#TaskTable")
.tablesorter({
sortList: [[2, 0], [1, 0]],
headers: {
0: { sorter: false },
2: { sorter: 'custom-date' }
}
})
.tablesorterPager({
container: $("#pager"),
size: 10
});
}
}
}
$(document).ready(function () {
// add parser through the tablesorter addParser method
$.tablesorter.addParser({
// set a unique id
id: 'custom-date',
is: function (s) {
// return false so this parser is not auto detected
return false;
},
format: function (s) {
s = '' + s; //Make sure it's a string
if (s.length == 0 || s == " ") {
return "ZZZ";
}
var hit = s.match(/(\d{2})-([A-Za-z]{3})-(\d{2})/);
if (hit && hit.length == 4) {
return hit[3] + months[hit[2].toUpperCase()] + hit[1];
}
else {
return s;
}
},
type: 'text'
});
LoadTaskJS();
});

Categories