Subgrid in jsgrid - javascript

I am trying to show the data history in jsgrid as asked here.
$("#jsGrid").jsGrid({
...
rowRenderer: function(item) {
var row = $("<tr>");
var historyGrid = $('<tr>').addClass('nested-grid').hide();
historyGrid.jsGrid({
width: "100%",
height: "auto",
editing: false,
data: [{"a":"d1","b": "d2"},{"a":"d3","b":"d4"},{"a":"d5","b":"d6"}],
heading: false,
fields: [{ name: "a", type: "text"}, {name: "b",type: "text"}]
})
var items= Object.keys(item);
items.forEach(function(key){
if(key!=items[items.length-1]) {
var cell = $("<td>").addClass("jsgrid-cell").append(item[key]);//line 1
row.append(cell);
}
});
row.click(function () {
historyGrid.toggle();
})
row.append(historyGrid);
return row.add(historyGrid);
}
});
The history appears as below. I want to display in such a way that, it spans the entire blank(row) area.
if I change it tr to td at line 1, it appears as below
Any help?

Related

remove selectedRow in handsontable using jQuery

I have an handsontable like the below image. After selecting any one of the rows (for example LastName) it should remove that particular row permanently. How can I achieve this using jQuery?
This is my code which I have written using the afterSelection function but I don't know how to delete that row.
this.tab.handsontable({
data: self.data,
dataSchema: {
columnsexpo: null,
placeholder: null
},
colHeaders: ['Columns Export'],
rowHeaders: true,
fixedColumns: true,
fillHandle: {
autoInsertRow: false,
},
columnSorting: true,
columns: [{
data: 'columnsexpo',
readOnly: true
}, ],
stretchH: 'all',
className: "htCenter",
height: 420,
afterChange: function() {},
beforeRemoveRow: function(row, col) {
var m = this.getDataAtCell(row, 0);
var mandatory = true;
self.MandatoryFields.forEach(function(item) {
if (!_.isEmpty(m)) {
var found = m.toLowerCase().includes(item.toLowerCase());
if (found) {
mandatory = false;
}
}
});
if (!mandatory) {
return false
} else
return true;
},
afterSelection: function(r, c) {
var da = this.getDataAtRow(r);
selectedRow = "";
selectedRow = da[0];
console.log(selectedRow);
},
afterRender: function() {
if (init) {
Events.trigger("DEW:ValidRequest", 1, self.checkValid());
}
init = true;
$('#tablesortable thead th div').filter(function() {
return $(this).text() == "Columns Export";
}).popup({
title: 'Columns Export',
position: 'top center'
});
}
});
EDIT
afterSelection: function(r,c,e){
var dat = this.getDataAtRow(r)
this.alter('remove_row', r, 1);
console.log(r);
},
Now after applying above function it is removing selected Row but if i select last row it is removing all previously selected row
use hot.alter('remove_row', 10, 2); inside after selection method of handsontable.
No need for jquery.
Or if you want to use jquery, store the handsontable instance in some varitable and call the same on row selection.
Update -- added deselectCell before removing the row. after removing the row, previous row is getting selected which is causing the problem.
afterSelection: function(r, c, e) {
this.deselectCell()
this.alter('remove_row', r, 1);
}

How to get databound function work with Kendo grid

I am trying to customize the style of grid cells depending on conditions met by cell values. In the kendo documentation I have found an example how to do this. The example works with extending the grid with a databound function.
I have adjusted the code on the Dojo page to my needs and there it works perfectly. But when I try to extend my grid with a databound function I fail to find the right syntax/postion to insert the function.
This is my databound function:
dataBound: function(e) {
// get the index of the cell
var columns = e.sender.columns;
var columnIndex = this.wrapper.find(".k-grid-header [data-field=" + "Frachtkonsens" + "]").index();
// iterate the table rows and apply custom row and cell styling
var rows = e.sender.tbody.children();
for (var j = 0; j < rows.length; j++) {
var row = $(rows[j]);
var dataItem = e.sender.dataItem(row);
var value = dataItem.get("Frachtkonsens");
var max = dataItem.get("Mengenschwelle");
//var min = dataItem.get("Min");
var cell = row.children().eq(columnIndex);
cell.addClass(checkValue(value, max));
}
}
This is the javascript:
<script type="text/javascript">
function checkvalue(value, max) {
if (max > 0) {
if (value > max){
return "critical";
}
}
}
$(function() {
var konsenseGrid = $("#parameters-grid").kendoGrid({
dataSource: someData,
scrollable: true,
sortable: true,
pageable: { refresh: true },
selectable: "row",
resizable: true,
height: 430,
editable: true,
toolbar: [{ text: "", template: kendo.template($("#add-parameter-template").html()) }, { text: "", template: kendo.template($("#update-parameter-template").html()) }],
columns: [
{
field: "Parameter",
title: "Parameter",
width: "160px"
},
{
field: "Max",
title: "Max",
width: "55px",
format: "{0:n}",
editor: numberEditor
},
{
field: "Frachtkonsens",
title: "Frachtkonsens",
width: "70px",
format: "{0:n1}",
editor: numberEditor
},
{
command:
["edit", "destroy"],
title: " ",
width: "200px"
}
],
});
});
And this is the style I want to apply to cells that meet the conditions:
.critical {
font-weight: bold;
color: #f00;
}
If someone could help me please!
Regards Manu
You should put dataBound along with the top-level configuration properties, and provide the respective handler function, e.g.:
$(function() {
var konsenseGrid = $("#parameters-grid").kendoGrid({
dataSource: {
data: [{'Parameter': 'a', Max: 5, Frachtkonsens: 10, Mengenschwelle: 5}, {'Parameter': 'b', Max: 1, Frachtkonsens: 1, Mengenschwelle: 3}]
},
dataBound: function(e) {
// get the index of the cell
var columns = e.sender.columns;
var columnIndex = this.wrapper.find(".k-grid-header [data-field='Frachtkonsens']").index();
// iterate the table rows and apply custom row and cell styling
var rows = e.sender.tbody.children();
for (var j = 0; j < rows.length; j++) {
var row = $(rows[j]);
var dataItem = e.sender.dataItem(row);
var value = dataItem.get("Frachtkonsens");
var max = dataItem.get("Mengenschwelle");
//var min = dataItem.get("Min");
var cell = row.children().eq(columnIndex);
cell.addClass(checkValue(value, max));
}
},
scrollable: true,
...
Example

Handsonetable - can't hide columns

I'm trying to hide few colums. Here is my code:
function setTable(options){
var data = options.data;
var container = options.container;
var dataSchema = options.dataSchema;
var colHeaders = options.colHeaders;
var columns = options.columns;
var table = new Handsontable(container, {
data: data,
disableVisualSelection:true,
dataSchema: dataSchema,
colHeaders:colHeaders,
columns:columns,
currentRowClassName: 'selected',
columnSorting:true,
columnStreching:true,
autoColumnSize: true,
stretchH: 'all',
outsideClickDeselects: false
});
Handsontable.hooks.add('afterSelectionEnd', function(e){
var data = this.getDataAtRow(e);
moveToAlert({
n:data[1],
v:data[4],
lt:data[7],
ln:data[8]
});
}, table);
Handsontable.hooks.add('afterOnCellMouseOver', function(e,c){
var data = this.getDataAtRow(c.row);
if(data[0] == null) return false;
moveToAlert({
n:data[1],
v:data[4],
lt:data[7],
ln:data[8]
})
}, table);
return table;
}
actualData.push(
{
reg:d.r,
name:d.n,
fd:d.fd,
td:d.td,
v:d.v,
rgps:d.rg,
loc:"PL, Wrocław, Autostradowa Obwodnica Wrocławia",
lt:d.lt,
ln:d.ln,
c:'a_'+d.c
}
);
}
if (TABLE_ACTUAL) TABLE_ACTUAL.destroy();
TABLE_ACTUAL = setTable({
data:actualData,
container:document.getElementById('actual-table'),
dataSchema:{reg: null, name: null, fd: null, td: null, v: null, rgps: null, loc: null, lt:null, ln:null,c:null},
colHeaders:["Pojazd", "Nazwa", "Od", "Do", "Wartość", "Droga", "Lokalizacja"],
columns:[
{
data:"reg",
editor:false,
},
{
data:"name",
editor:false,
},
{
data:"fd",
editor:false,
},
{
data:"td",
editor:false,
},
{
data:"v",
editor:false,
},
{
data:"rgps",
editor:false,
},
{
data:"loc",
editor:false,
}
],
});
So i want to hide 3 last columns ( lt,ln,c) and also disable editor on all colums. Why this way not working? I dont want to use customrender becouse i think its unnecessary.
EDIT
SOLVED (thanks to #ZekeDroid)
I used getSourceDataAtRow() instead of getDataAtRow().
Also used fix for sorted table: http://docs.handsontable.com/0.16.1/demo-sorting-data.html and more specifically this : physicalIndex = instance.sortIndex[logicalIndex][0]; as a index for selected row.
It's likely due to the dataSchema option. You are including the columns to show there, even if null. Try removing the dataSchema option entirely. But please provide a fiddle so we can be more sure about it.

SlickGrid button click handler stops functioning on scroll event?

In attempting to use SlickGrid in my page, I have noticed that a jQuery click handler I declare after the grid is rendered only works for approximately 2x the number of rows visible.
Moreover, when a button is clicked the value property is changed to provide visual confirmation to the user. However, upon scrolling too far down past one of the previously clicked buttons, scrolling back up appears to reset the value to the original/default value.
As far as I can tell, it looks like the grid is re-rendering at various intervals. If that suspicion is correct, how do I preserve the effect of the click handler and the values in those buttons already clicked?
It may be important to note that I am not using dataView.
<script type="text/javascript">
var j$ = jQuery.noConflict();
var grid,
data = [],
columns = [
{ id: "rownum", name: "Row #", field: "rownum", width: 50 },
{ id: "accname", name: "Account Name", field: "accname", width: 500 },
{ id: "accid", name: "Id", field: "accid", width: 150 },
{ id: "rectypeid", name: "Record Type ID", field: "rectypeid", width: 150 },
{ id: "itemurl", name: "Item URL Link", field: "itemurl", width: 300, formatter: function (r,c,v,def,datactx) { return "<a target='_blank' href='" + v + "'>" + v + "</a>" } },
{ id: "rfrbtn", name: "Notify Staff", field: "rfrbtn", width: 75, formatter: function (r,c,v,def,datactx) { return "<input class='rfrch' value='Yes' type='button' id='" + datactx.accid + "'/>" } }
],
options = {
enableCellNavigation: false,
enableColumnReorder: true,
};
var acc = new SObjectModel.Acc();
// Query Accounts
var count = 1;
acc.retrieve({ where: {Name: {like: '%Test Acct%'}, RecordTypeId: {eq: '01230000003MJmr'}}, limit: 100 }, function(err, records, event){
if(err) {
alert(err.message);
}
else {
records.forEach(function(record) {
data.push({
rownum: count++,
accname: record.get("Name"),
accid: record.get("Id"),
rectypeid: record.get("RecordTypeId"),
itemurl: record.get("itemurl")
});
});
}
grid.invalidate();
rfrClickHandler();
});
grid = new Slick.Grid("#container", data, columns, options);
var rfrClickHandler = function() {
j$(".rfrch").click(function() {
var rfrbtnClicked = j$(this).prop('id');
j$(this).prop('value','Cancel');
console.log(rfrbtnClicked);
});
}
</script>
Use .on() so that you do not have to re-bind the click handlers after the rows are re-rendered.
j$("#container").on('click', '.rfrch', function(){
//... your handler code
}
In your formatter for the button you can add a property to dataContext for the current value state of the button and also a data property to hold the row index:
if(datactx.rfrchState === undefined){
datactx.rfrchState = "Yes";
}
return "<input class='rfrch' value='"+datactx.rfrchState+"' data-row-index='"+r+"' type='button' id='" + datactx.accid + "'/>"
Then in your button handler add code to retrieve the data object and set rfrchState. That way when you scroll up and down and the rows are re-rendered the state will be preserved and set on the button via the formatter.
var rowIndex = j$(this).data('row-index');
var dataItem = grid.getDataItem(rowIndex);
dataItem.rfrchState = dataItem.rfrchState === 'Yes'?'No':'Yes';
Hope this helps.

In jqxGrid, how do I add a new calculated column from JSON data?

In jqxGrid, how do I add a new calculated column from JSON data?
My JSON data has fields baseQuantity and unitCost. I want to add a new field called totalCost which would be baseQuantity * unitCost.
I'm trying to add the data using loadComplete, but it doesn't seem to work.
ANOTHER alternative I could do is to loop through objData and inject a new field with the calculated value. But aside from that, is there any way I could do it via jqxGrid's API?
var jsonString = [{ "baseQuantity":"1", "unitCost":"2"}, { "baseQuantity":"3", "unitCost":"4"}];
var objData = $.parseJSON(jsonString);
var srcData = {
datatype: "json",
datafields: [
{ name : 'baseQuantity', type : 'number' },
{ name : 'unitCost', type : 'number' }
],
localdata : objData
};
var adapterData = new $.jqx.dataAdapter(srcData, {
loadComplete: function (records) {
var modifiedDataArray = new Array();
for (var i = 0; i < records.length; i++) {
var modifiedData = records[i];
modifiedData.totalPayment = modifiedData.baseQuantity * modifiedData.unitCost;
modifiedDataArray.push(programme);
}
return modifiedDataArray;
}
});
$('div#jqxGrid').jqxGrid({
width: '100%',
source: adapterData,
theme: getTheme(),
pageable: true,
autoheight: true,
sortable: true,
altrows: true,
columns: [
{ datafield: 'baseQuantity', text: 'Base Qty.', width: 120 }
{ datafield: 'unitCost', text: 'Unit Payment' , width: 120 }
]
});
Use the cellrenderer function:
http://www.jqwidgets.com/jquery-widgets-documentation/documentation/jqxgrid/jquery-grid-api.htm
{ text: 'totalCost', datafield: 'totalCost', width: 70, cellsalign: 'right', columntype: 'number',
cellsrenderer: function (row, columnfield, value, defaulthtml, columnproperties) {
var rowData = $("#jqxGrid").jqxGrid('getrowdata', row);
return rowData.baseQuantity * rowData.unitCost;
}
}
Don't use the event "loadComplete" but "beforeLoadComplete" instead. Here is an example :
var dataAdapter = new $.jqx.dataAdapter(source,
{
beforeLoadComplete: function (records) {
records[0]['firstname'] = "Michael";
return records;
}
}
);
Than you can loop through all records, and generate you computed column. This is the official solution they seems to give here : http://www.jqwidgets.com/community/topic/computed-column/

Categories

Resources