Sorting a column display hidden rows in jqGrid - javascript

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.

Related

Datatables: dropdown in a cell

i'm trying to generate a table with Datatables.
I receive a json from my controller, here a sample:
this json can change (number of columns, name of the columns) and I can build my table with the good number of column and the good name.
My question is:
How can i do to have a dropdown when the "liste" have an array and a simple input when it's null?
Is it even possible?
EDIT :
I forget to explain something. The Json that I receive is a json to build the table not to fill it. So is it possible to do a columnsDef before the datas are in the cell.
EDIT n°2:
I used the solution that I accepted, but the problem was with my json. I tried to send a json to build and a json to fill the table. So I change my json and I send the list of options in the json to fill the table.
Hope it will help other people.
Thanks
Here are two solutions:
1) With a drop-down.
2) With a formatted array (as an alternative).
1) With a Dropdown
The end result looks like this:
The datatables definition is this:
<script type="text/javascript">
var dataSet = { "records" : [
{ "data" : "123456789",
"liste" : null,
"name" : "Nombre Enfants"
},
{ "data" : "5678901234",
"liste" : [ "Oui", "Non" ],
"name" : "Transport"
}]};
$(document).ready(function() {
$('#example').DataTable( {
data: dataSet.records,
columnDefs: [
{ targets: [ 0 ],
title: "Data",
data: "data" },
{ targets: [ 1 ],
title: "Liste",
data: function ( row ) {
if (row.liste == null) {
return null;
} else {
return buildDropdown(row.liste);
}
} },
{ targets: [ 2 ],
title: "Name",
data: "name" }
]
} );
function buildDropdown(data) {
var dropdown = "<select>";
for (var i = 0; i < data.length; i++) {
var option = "<option value=\"" + data[i] + "\">" + data[i] + "</option>";
dropdown = dropdown + option;
}
dropdown = dropdown + "</select>";
return dropdown;
}
} );
</script>
It builds a drop-down based on the assumption that a non-null value is an array. This may not always be the case in your data - just an assumption on my part.
2) With a formatted array
Just in case this is also of interest, DataTables has a built-in syntax for formatting array data, so it is displayed in a cell like this:
In this case, you no longer need the drop-down builder function. Everything else is the same as option (1) except for this part:
{ targets: [ 1 ],
title: "Liste",
data: "liste[, ]" },
Specifically, the [, ] notation lets you format the array data.
I mention this only because it lets you display all the array data in the cell, rather than neeeding to click a drop-down. But that is just a suggestion.
You may find that other functions such as searching and sorting are better with this option.
Update
The question has clarified that the table needs to be built dynamically from the data provided in the JSON.
You can pass variables to the datatables initializer - for example:
var col1 = { targets: [ 0 ], title: "Data", data: "data" };
var col2 = { targets: [ 1 ], title: "Liste", data: "liste" };
var col2 = { targets: [ 2 ], title: "Name", data: "name" };
var dynamicCols = [ col1, col2, col3 ];
The above col1 variable defines the title for the column, and where the column will get its data (from the dataSet.data fields).
The dynamicCols variable can then be used in a columnDefs as follows:
$(document).ready(function() {
$('#example').DataTable( {
data: dataSet.records,
columnDefs: dynamicCols
} );
However, I am not aware of a way to include a function in a columndef, using this approach (for example to present a cell's data as a drop-down, if needed).
There are additional techniques which can be used to make a datatable even more dynamic - several examples are available online - for example here. Without seeing a more detailed example of the JSON being provided, I am not sure if there are any additional suggestions I can make.

Extjs 4.2.1 Local filtering of Grid panel with Paging

Fiddle with the problem is here https://fiddle.sencha.com/#view/editor&fiddle/2o8q
There are a lot of methods in the net about how to locally filter grid panel that have paging, but no one is working for me. I have the following grid
var grid = Ext.create('Ext.grid.GridPanel', {
store: store,
bbar: pagingToolbar,
columns: [getColumns()],
features: [{
ftype: 'filters',
local: true,
filters: [getFilters()],
}],
}
Filters here have the form (just copy pasted part of my filters object)
{
type: 'string',
dataIndex: 'name',
active: false
}, {
type: 'numeric',
dataIndex: 'id',
active: false
},
The store is the following
var store = Ext.create('Ext.data.Store', {
model: 'Store',
autoLoad: true,
proxy: {
data: myData,
enablePaging: true,
type: 'memory',
reader: {
type: 'array',
}
},
});
Here myData - comes to me in the form of
["1245", "Joen", "Devis", "user", "", "email#com", "15/6/2017"],
["9876", "Alex", "Klex", "user", "", "email#com", "15/6/2017"],[...
Also I have the the pagingToolbar
var pagingToolbar = Ext.create('Ext.PagingToolbar', {
store: store, displayInfo: true
});
So all the elements use the store I declared in the top. I have 25 elements per grid page, and around 43 elements in myData. So now I have 2 pages in my grid. When I am on first page of grid and apply string filter for name, for example, it filters first page (25 elements), when I move to 2d page, grid is also filtered, but in scope of second page. So as a result each page filters seperately. I need to filter ALL pages at the same time when I check the checkbox of filter, and to update the info of pagingToolbar accordingly. What I am doing wrong?
Almost sure that it is a late answer, but I have found the local store filter solution for paging grid you are probably looking for:
https://fiddle.sencha.com/#fiddle/2jgl
It used store proxy to load data into the grid instead of explicitly specify them in store config.
In general:
create empty store with next mandatory options
....
proxy: {
type: 'memory',
enablePaging: true,
....
},
pageSize: 10,
remoteFilter: true,
....
then load data to the store using its proxy instead of loadData
method
store.getProxy().data = myData;
store.reload()
apply filter to see result
store.filter([{ property: 'name', value: 'Bob' }]);
See President.js store configuration in provided fiddle example for more details.
Hope it helps

Javascript library for table rendering

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.

ExtJS 6 grid doesn't update/refresh column headers properly

I've got a basic ExtJS gridpanel on which I can apply custom state on the fly. Using another control such as a combobox or another grid, my application applies the selected state on the grid. An example of this state:
{
"height": 384,
"columns": [{
"id": "h107"
},
{
"id": "h1",
"width": 30
},
{
"id": "unplannedtasks_ActualEndDate",
"hidden": true,
"width": 100
},
{
"id": "unplannedtasks_ActualNoResources",
"hidden": true,
"width": 100
},
{
"id": "unplannedtasks_ActualResponseDateTime",
"hidden": true
},
{
"id": "unplannedtasks_ActualTotalDurationInSeconds",
"width": 100
},
"filters": []
}
Here's the corresponding columns section of the grid declaration:
Ext.define('Ext.grid.Stateful', {
extend: 'Ext.grid.Panel',
stateEvents: ['columnmove', 'columnresize', 'sortchange', 'hiddenchange', 'groupchange', 'show', 'hide'],
// CODE OMMITTED FOR BREVITY
initComponent: function () {
Ext.apply(this, {
columns: [
filterAction,
new columns.tasks.ActualEndDate({ id: 'unplannedtasks_ActualEndDate', hidden: false }),
new columns.tasks.ActualNoResources({ id: 'unplannedtasks_ActualResponseDateTime', hidden: false },
new columns.tasks.ActualResponseDateTime({ id: 'unplannedtasks_ActualResponseDateTime', hidden: false },
new columns.tasks.ActualTotalDurationInSeconds({ id: 'unplannedtasks_ActualTotalDurationInSeconds', hidden: false }
]
});
}
})
An example of a column definition:
Ext.define("columns.tasks.ActualNoResources", {
extend: "Ext.grid.column.Column",
text: 'ActualNoResources',
dataIndex: 'ActualNoResources',
editor: {
allowBlank: false
}, filterable: true,
filter: {
type: 'string'
}
});
Everything goes as I expected except the column headers don't seem to refresh properly. If I open the columns panel in the grid, it is showing the correct amount of visible and hidden columns. Same story with the filters: if there's a filter in the state, it applies the correct value on the correct field. It's as though the column headers need to be refreshed in some way.
I tried to use grid.getView().refresh() but that doesn't work. Instead, if I resize the grid, it does refresh the hidden columns but not the columns that were initially hidden but now visible.
I think I am missing a simple line of code that belongs in the applyState method of the grid so I can command the grid to refresh the grid with the new state rather than the previous or initial state.
Any ideas on how to solve this?
As it turns out, the scenario that I pursue is not possible out of the box with ExtJS. What I'm asking can only be done during startup (without intervention of a developer's custom code) so I had to quit this approach and provide custom code. In the end, I had to rebuild the columns and then pass that collection to the reconfigure(store, columns) method of the grid.

Insert New Column To Kendo Datagrid

I Got Columns are quantity,Totalprice in my kendo grid. Then I want to add calculated column to my datagrid.
for example:
$("#gridcolumnadd").click(function (e) {
//1.add new column code Column Name is "Price For per kg"
//2.Set Column type is number
//3.Set Column aggregate is sum for footerTemplate
//4.add calculated values ex:(Totalprice/quantity) to "Price For per kg" with using for loop row count.
//redraw datagrid
});
Is possible to make it in kendo datagrid?
**
NOTE
I WANT TO CREATE DATAGRID FIRSTLY THEN ADD NEW COLUMN WITH ITS CALCULATION. THATS THE REASON "I WRITE JUST BUTTON CLICK"
**
For example; It is not working
var raw = grid.dataSource.data();
var length = raw.length;//if ı have many data . I can use For Loop
raw[0].new="Test"; //I think one data we have it
grid.columns.push({ field: "new" });
grid.dataSource.data(raw);
Some tips:
Instead of adding a column you should show and hide a column otherwise you will have to destroy current grid and create a new one (pretty expensive).
Have it created from the beginning. You might have fields in your model that are actually not coming from the server or you can have fields that are not in the model. You should decide.
Don't understand what do you mean by Set Column aggregate is sum for footerTemplate. As far as I understand you want to define an aggregate of a column so you should take a look into columns.aggregate.
Is this an editable grid? If not I do recommend to compute it when you receive the data from the server using either dataBound event handler or even using DataSource schema.parse
Lets see how this fits together...
This is my original schema:
schema: {
model: {
id: "ProductID",
fields: {
ProductID: { type: "number" },
ProductName: { type : "text" },
UnitPrice: { type: "number" },
UnitsInStock: { type: "number" }
}
},
...
The first thing is add the Total which equals UnitPrice times UnitsInStock where I'm going to use parse.
schema: {
model: {
id: "ProductID",
fields: {
ProductID: { type: "number" },
ProductName: { type : "text" },
UnitPrice: { type: "number" },
UnitsInStock: { type: "number" },
Total: { type: "total" }
}
},
parse : function (d) {
$.each(d, function(idx, elem) {
elem.Total = elem.UnitPrice * elem.UnitsInStock;
})
return d;
}
},
as you can see I've added an extra field Total and then in parse I iterate to compute the total for each record.
Next is define an aggregate that computes the total for all the data received.
aggregate: [
{ field: "Total", aggregate: "sum" }
]
This simple!
Now lets define the columns of my grid:
columns: [
{ field: "ProductName", title : "Name" },
{ field: "UnitPrice", title: "Price" },
{ field: "UnitsInStock", title:"Units" },
{
field: "Total",
title:"Total",
hidden: true,
aggregates: [ "sum" ],
footerTemplate: "#= sum #"
}
]
Here what is important is Total column where:
* I define as (initially) hidden using hidden: true.
* I also define an aggregate that is the sum.
* And finally I define a template for printing it.
Finally, I don't need to redraw the grid, it is enough invoking columnShow...
$("#gridcolumnadd").click(function (e) {
$("#grid").data("kendoGrid").columnShow(3);
});
All this together here : http://jsfiddle.net/OnaBai/63mg9/

Categories