Javascript library for table rendering - javascript

I need to show an array of objects in the table like representation. Table has columns with the properties, and when clicked on the column it should show more data inside the table. It should be sortable.
Is there a JS library that could do this, so I dont have to write this from scratch?
Please see the attached image with the JSON object.
When the user clicks on Ana, additional row is inserted.

I created the demo https://jsfiddle.net/OlegKi/kc2537ty/1/ which demonstrates the usage of free jqGrid with subgrids. It displays the results like
after the user clicks on the "+" icon in the second line.
The corresponding code you can find below
var mydata = [
{ id: 10, name: "John", lname: "Smith", age: 31, loc: { location: "North America", city: "Seattle", country: "US" } },
{ id: 20, name: "Ana", lname: "Maria", age: 43, loc: { location: "Europe", city: "London", country: "UK" } }
];
$("#grid").jqGrid({
data: mydata,
colModel: [
{ name: "name", label: "Name" },
{ name: "lname", label: "Last name" },
{ name: "age", label: "Age", template: "integer", align: "center" }
],
cmTemplate: { align: "center", width: 150 },
sortname: "age",
iconSet: "fontAwesome",
subGrid: true,
subGridRowExpanded: function (subgridDivId, rowid) {
var $subgrid = $("<table id='" + subgridDivId + "_t'></table>"),
subgridData = [$(this).jqGrid("getLocalRow", rowid).loc];
$("#" + subgridDivId).append($subgrid);
$subgrid.jqGrid({
idPrefix: rowid + "_",
data: subgridData,
colModel: [
{ name: "location", label: "Localtion" },
{ name: "city", label: "City" },
{ name: "country", label: "Country" }
],
cmTemplate: { align: "center" },
iconSet: "fontAwesome",
autowidth: true
});
}
});
Small comments to the code. Free jqGrid saves all properties of input data in data parameter. I added id property to every item of input data. It's not mandatory, but it could be helpful if you would add more functionality to the grid. See the introduction for more details.
The columns are sortable based on the type of the data specified by sorttype property of colModel. To simplify usage some standard types of data free jqGrid provides some standard templates which are shortcurts for some set of settings. I used template: "integer" in the demo, but you could replace it to sorttype: "integer" if only sorting by integer functionality is important.
If the user click on "+" icon to expand the subgrid then jqGrid inserts new row and creates the div for the data part of the subgrid. You can replace subGridRowExpanded from above example to the following
subGridRowExpanded: function (subgridDivId) {
$("#" + subgridDivId).html("<em>simple subgrid data</em>");
}
to understand what I mean. The unique id of the div will be the first parameter of the callback. One can create any common HTML content in the subgrid. Thus one can create empty <table>, append it to the subgrid div and
then convert the table to the subgrid.
To access to the item of data, which corresponds to the expanding row one can use $(this).jqGrid("getLocalRow", rowid). The return data is the item of original data. It has loc property which we need. To be able to use the data as input for jqGrid we create array with the element. I's mostly all, what one have to know to understand how the above code works.
You can add call of .jqGrid("filterToolbar") to be able to filter the data or to add pager: true (or toppager: true, or both) to have the pager and to use rowNum: 5 to specify the number of rows in the page. In the way you can load relatively large set of data in the grid and the user can use local paging, sorting and filtering. See the demo which shows the performance of loading, sorting and filtering of the local grid with 4000 rows and another one with 40000 rows. All works pretty quickly if one uses local paging and not displays all the data at once.

I use datatables.net for all my "more complex than lists"-tables. I It's a very well kept library with loads of features and great flexibility.
In the "con" column I would say that it's so complex that it probably has quite a steep learning curve. Although the documentation is great so there is always hope for most problems.

Related

How can you format a Tabulator SELECT based header filters options?

We are using Tabulator (4.8.3) and have a SELECT based header filter on one column. It all works great except we are trying to add some formatting to some of the select options. They display in the select dropdown with the formatting as expected. However once a selection is made, the selected text displays with the raw html (not formatted).
A JS fiddle here shows what we mean. Make a selection and see the formatting displayed in the selection text (e.g. the bold tags and non-breaking spaces).
We looked for a headerFilterFormatter or something along those lines in Tabulator but could not find anything. We also saw this post:
How do I create a multi-select header filter in tabulator?, but it seems like overkill to write all this just to sanitize option texts display.
We don't care id the selected text is formatted or not, we just don't want the html displaying in the value. We could possibly sanitize it externally every time a selection is made, but that does not seem like a great idea because it will tightly couple everything.
Does anyone know if there is a quick, easy way to address this in Tabulator?
var table = new Tabulator("#table", {
layout: "fitDataFill",
columns: [{
title: "ID",
field: "id"
},
{
title: "Topic",
field: "topic",
width: 120,
headerFilterPlaceholder: "-- Select --",
headerFilter:"select",
headerFilterParams: {values: paramLookup}
},
],
});
var tableData = [{
id: 1001,
topic: "1.0",
},
{
id: 1002,
topic: "1.1",
},
{
id: 1003,
topic: "2.0",
},
{
id: 1004,
topic: "3.0",
},
];
function paramLookup(cell){
return {
"1.0":"<b>1.0</b>",
"1.1":" 1.1",
"2.0":"<b>2.0</b>",
"3.0":"<b>3.0</b>",
};
}
table.setData(tableData);
The problem you are facing is you are trying to style the labels for the select list values in the values array. The select editor uses an input element to show the selected value, therefor when you are selecting a value it is showing the label as text.
The correct approach is to include the actual value in the label and then use the listItemFormatter to format the list as wanted, that way you store a plain text value against the label and display it as html:
{
title: "Topic",
field: "topic",
width: 120,
headerFilterPlaceholder: "-- Select --",
headerFilter:"select",
headerFilterParams: {
values: [1.0, 1.1, 1.2],
listItemFormatter:function(value, title){
return "<b>" + title + "</b>";
},
}
},

Sorting a column display hidden rows in jqGrid

I have some rows I hide like that:
$("#"+rowid).hide();
My problem is that when the user clicks to sort a colmun, the hidden rows reappeared. There is a way to avoid this?
EDIT
I will try to explain a little bit more what I did with code example.
I start to create my grid with this params (and without datas).
var params = {
datatype: "local",
data: [],
caption: "Grid",
colNames:[ "Column A", "Column B" ],
colModel:[
{ name:"colA", key: true },
{ name:"colB" }
]
};
For some reasons, I reload next the grid with datas, like this:
$("#myGrid").jqGrid("clearGridData")
.jqGrid("setGridParam", { data: myDatas })
.trigger("reloadGrid");
And I have checkboxes with listeners, like this one:
$("#checkbox1").on("change", onCheckbox1Changed);
function onCheckbox1Changed() {
var rowid = ...;
var datas = $("#myGrid").jqGrid("getRowData");
for(var key in datas) {
if(datas[keys].colB === "" && $("#checkbox1").val() === true) {
$("#"+rowid).show();
} else if(datas[keys].colB === "" && $("#checkbox1").val() === false) {
$("#"+rowid).hide();
}
}
}
This code works like I want. Rows are hidden/shown depending on checkboxes. The problem is when I clik on a column to sort it, the hidden columns reappeared.
EDIT 2
I could force the grid to hide the rows after a sort. But I didn't find where I can find an event like "afterSort". There is "onSortCol" but it is called before the sort.
A solution will be to force that using "loadComplete". Like this:
var params = {
// ...
loadComplete: onLoadComplete
}
function onLoadComplete() {
onCheckbox1Changed();
}
I tried it and it works. But I am not very "fan" with this solution.
I find hiding some rows after displaying the page of data not the best choice. The main disadvantage is the number of rows which will be displayed. You can safe use $("#"+rowid).hide(); method inside of loadComplete only if you need to display one page of the data. Even in the case one can see some incorrect information. For example, one can use viewrecords: true option, which place the text like "View 1 - 10 of 12" on right part of the pager.
I personally would recommend you to filter the data. You need to add search: true option to the grid and specify postData.filters, which excludes some rows from displaying:
search: true,
postData: {
filters: {
groupOp: "AND",
rules: [
{ field: "colA", op: "ne", data: "rowid1" },
{ field: "colA", op: "ne", data: "rowid2" }
]
}
}
If you would upgrade from old jqGrid 4.6 to the current version (4.13.6) of free jqGrid, then you can use "ni" (NOT IN) operation:
search: true,
postData: {
filters: {
groupOp: "AND",
rules: [
{ op: "ni", field: "id", data: "rowid1,rowid2" }
]
}
}
In both cases jqGrid will first filter the local data based on the filter rules and then it will display the current page of data. As the result you will have the perfect results.
Sorting of such grid will not not change the filter.
Don't hide columns after the creation of the table, hide them directly when you create the grid using the option hidden, like this:
colNames: ['Id', ...],
colModel: [
{ key: true, hidden: true, name: 'Id', index: 'Id' },
....
]
If you want to hide columns on particular events after the creation of the grid, look at this article.
Hope it was you were looking for.

jqGrid how handle event enter key after edit column thanks to editRow?

I am starting to use the jQuery plug in jqGrid for rendering nice tables, I want to make just one column editable.
I manage to render a table where a textbox come up when i click on my editable column, nevertheless I don't manage to catch when a cell has been edited (after enter has been pressed) . When I read doc, I suppose I have to use aftersavefunc but I don't know where and how it has to be used.
Could you help me please?
Bellow my exemple I would like to complete.
var mydata = [{
name: "Toronto",
country: "Canada",
continent: "North America"
}, {
name: "New York City",
country: "USA",
continent: "North America"
}, {
name: "Silicon Valley",
country: "USA",
continent: "North America"
}, {
name: "Paris",
country: "France",
continent: "Europe"
}]
function edit(id) {
var table = jQuery(this);
table.jqGrid('editRow', id,
{
keys: true,
});
}
$("#grid").jqGrid({
data: mydata,
datatype: "local",
colNames: ["Name", "Country", "Continent"],
colModel: [{
name: 'name',
index: 'name'
}, {
name: 'country',
index: 'country',
editable: true,
}, {
name: 'continent',
index: 'continent'
}],
onSelectRow: edit
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqgrid/4.6.0/js/jquery.jqGrid.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqgrid/4.6.0/js/i18n/grid.locale-en.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqgrid/4.6.0/css/ui.jqgrid.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/i18n/jquery-ui-i18n.js"></script>
<table id="grid"></table>
You can specify aftersavefunc for example together with other options of editRow:
table.jqGrid('editRow', id, {
keys: true,
url: "myServerUrl", // it's optional
aftersavefunc: function (rowid) { // can add jqXHR, sentData, options
alert(rowid + " is saved");
}
});
The next problem: I would strictly recommend you to add id property in the input data used for filling the grid. The id property will be saved as the value of id attribute of every row (<tr>) element, used in callbacks and will be send to the server on editing. I'd recommend you to remove all index properties from jqGrid too and add the option autoencode: true to jqGrid. If you use old 4.6 version then you should add gridview: true option to improve the performance of the grid and to add height: "auto" option too.
The next problem: it's recommended to save/discard previously edited row inside of onSelectRow. You need call saveRow or restoreRow. You current code can produces many simultaneously edited rows. The user can forget to press Enter and thought that the rows are already modified. I'd recommend you to add at least navigator bar with edit/save/cancel buttons by inlineNav additionally to your current code. It helps some users to save the rows.
One more remark. jqGrid 4.6 is already old. There are currently two main forks of jqGrid: free jqGrid in the current version 4.13.0 and commercial version Guriddo jqGrid JS. Both versions contains many new features, but there will be more and more different. I develop free jqGrid after the post about renaming jqGrid to Guriddo jqGrid JS and changing the license agreement. I provided free jqGrid under the same licenses (MIT and GPLv2) like old versions of jqGrid (4.6 for example). You can use it from CDNs too (see the wiki article). jqGrid 4.6 is dead. No bug fix or new feature will be developed. You wrote that you are starting to use jqGrid. In the case it's especially bad to use some old version.

Extjs 6 combobox values and display values not displaying correctly when setting values dynamically per row

Oof that was a long title.
In my current project I have a grid that holds a set of workshop records. For each of these workshops there is a set of rates that apply specifically to the given workshop.
My goal is to display a combobox for each row that shows the rates specific to that work shop.
I've got a prototype that works for the most part up on sencha fiddle, but there's something off about how the selection values are being created:
Ext.define('Rates',{
extend: 'Ext.data.Store',
storeId: 'rates',
fields: [
'rateArray'
],
data:[
{
workshop: 'test workshop 1',
rateArray: {
rate1: {show: "yes", rate: "105", description: "Standard Registration"},
rate3: {show: "Yes", rate: "125", description: "Non-Member Rate"},
rate4: {show: "yes", rate: "44", description: "Price for SK tester"}
}
},
{
workshop: 'test workshop 2',
rateArray: {
rate1: {show: "yes", rate: "10", description: "Standard Registration"},
rate2: {show: "yes", rate: "25", description: "Non-Member Registration"}
}
}
]
});
Ext.define('MyGrid',{
extend: 'Ext.grid.Panel',
title: 'test combo box with unique values per row',
renderTo: Ext.getBody(),
columns:[
{
xtype: 'gridcolumn',
text: 'Name',
dataIndex: 'workshop',
flex: 1
},
{
xtype: 'widgetcolumn',
text: 'Price',
width: 200,
widget:{
xtype: 'combo',
store: [
// ['test','worked']
]
},
onWidgetAttach: function (column, widget, record){
var selections = [];
Ext.Object.each(record.get('rateArray'), function (rate, value, obj){
var desc = Ext.String.format("${0}: {1}", value.rate, value.description);
// according to the docs section on combobox stores that use 2 dimensional arrays
// I would think pushing it this way would make the display value of the combobox
// the description and the value stored the rate.
selections.push([rate, desc]);
});
console.log(selections);
widget.getStore().add(selections);
}
}
]
});
Ext.application({
name : 'Fiddle',
launch : function() {
var store = Ext.create('Rates');
Ext.create('MyGrid',{store: store});
}
});
In the grid widget that I'm using for the combobox I'm using the onWidgetAttach method to inspect the current row's record, assemble the rate data from the record into 2 dimensional array, and then setting that to the widget's store.
When I look at the sencha docs section on using a 2 dimensional array as the store, it states:
For a multi-dimensional array, the value in index 0 of each item will be assumed to be the combo valueField, while the value at index 1 is assumed to be the combo displayField.
Given that, I would expect the combo box to show the assembled description (e.g.
"$150: Standard Registration") and use the object key as the actual stored value (e.g. "rate1").
What I'm actually seeing is that the display value is the rate and I'm not sure how sencha generates the combobox selections to see how the selection is being rendered out.
Is my assumption about how the 2-dimensionally array gets converted to the store wrong?
Well, your question is suffering from the XY problem. Because what you really want to do is the following:
You want to create a decent store for your combo, using a well-defined model with the meaningful column names you already have in "rateArray", then you define displayField and valueField accordingly, and in onWidgetAttach, just stuff the "rateArray" object into that store using setData.
Sth. along the lines of
xtype: 'widgetcolumn',
text: 'Price',
width: 200,
widget:{
xtype: 'combo',
store: Ext.create('Ext.data.Store',{
fields:['rate','description','show']
filters:[{property:'show',value:"yes"}]
}),
displayField:'description',
valueField:'rate',
onWidgetAttach: function (column, widget, record){
widget.getStore().setData(record.get("rateArray"));
}
},

Kendo UI Grid column headerTemplate function does not get access to the column definition

I'm trying to use the columns.headerTemplate feature of a Kendo UI Grid to customise the column header. You use this feature as shown below and as demonstrated by this example I created. Normally when using Kendo UI templates, the widget will pass the entity into template function so you can use the various properties to customise the html to be rendered.
Debugging the Kendo UI Grid code I can see that in the _headerCellText method the call to the template function passes in an empty object rather than the column even though column object is in scope.
text = kendo.template(template, settings)({});
Is there another approach I can take before resorting to custom column header templates for each column or worse - jQuery manipulation of the widget rendered DOM?
Is there a good reason for deviating from the common template pattern in the framework for this use case?
// Example kendoGrid use of column.headerTemplate
var templateFunction = function(shouldBeColumn) {
// shouldBeColumn is an empty object rather than the column object
return "Useless object:" + kendo.stringify(shouldBeColumn);
};
$("#grid").kendoGrid({
dataSource: {
data: products,
pageSize: 20
},
height: 550,
scrollable: true,
columns: [
{ field: "ProductName", title: "Product Name" },
{ field: "UnitPrice", title: "Unit Price", headerTemplate: plainTemplate },
{ field: "UnitsInStock", title: "Units In Stock", headerTemplate: templateFunction }
]
});
RE: "Is there another approach I can take before resorting to custom column header templates for each column or worse - jQuery manipulation of the widget rendered DOM?"
Invoke a wrapper function that returns a function, thus:
function createHeaderTemplate(columnName) {
return function() {
return "Custom: " + columnName;
};
}
...
columns: [
{ field: 'field', headerTemplate: createHeaderTemplate('My Field') },
{ field: 'field2', headerTemplate: createHeaderTemplate('My 2nd Field') }
]

Categories