extend jqgrid for colModel edittype - javascript

I am going to use JqGrid for many different web pages.
And I have some custom formatter, and custom edittype
for example, I want to use datepicker to edit dates
so, instead of using colModel's edittype as custom, and provide custom functions to do that, I would like "if possible" to write an extension to jqgrid edittype, so I can just write "date", and I will write an extension to replace it with the datepickeer.
As I said, it is for re-usability, so instead of doing custom edit type for every web page/jqgrid, I could do it only once in that place.
Is there any documentation on how to extend jqgrid?

I would start with custom formatter. jqGrid support predefined formatters like formatter: "integer", formatter: "date". You can "register" your custom formatter and unformatter as one more value which you can use. For example if you want to register formatter: "myCheckbox" you need define $.fn.fmatter.myCheckbox as formetter function and $.fn.fmatter.myCheckbox.unformat as unformatter function.
$.extend($.fn.fmatter, {
myCheckbox: function (cellValue, options, rowObject) {
// the code of the custom formatter is here
...
}
});
$.extend($.fn.fmatter.myCheckbox, {
unformat: function (cellValue, options, elem) {
// the code of the custom unformatter is here
...
}
});
The code from here uses Font Awesome 4.x and register new formatter: "checkboxFontAwesome4". "Registering" of custom formatters can simplify your code.
The next feature. jqGrid supports column templates starting with version 3.8.2 jqGrid (see the old answer). It allows you to define common settings used in colModel as one object and to use template property in colModel. For example if you have many columns which contains numbers you can define for example numberTemplate object as
var numberTemplate = {
formatter: "number", align: "right", sorttype: "number", width: 60,
searchoptions: {
sopt: ["eq", "ne", "lt", "le", "gt", "ge"]
}
};
then you can define tree columns "tax", "amount" and "total" as
colModel: [
...
{ name: "tax", template: numberTemplate },
{ name: "amount", template: numberTemplate },
{ name: "total", width: 70, template: numberTemplate },
...
]
In the way you defines columns where all the properties from numberTemplate will be applied in the columns. The default width: 60 defined in numberTemplate will be overwritten to the value width: 70 for the column "total".
The usage of column templates allows you to define once in your code templates for dates which uses jQuery UI Datepicker for example and uses in every column of every grid of your project just the corresponding reference on the template.
The current version of jqGrid on github supports "registering" of templates as strings. So the next version (higher as 4.6.0), which I hope will be soon released, will support the following syntax:
$.extend($.jgrid, {
cmTemplate: {
myNumber: {
formatter: "number", align: "right", sorttype: "number",
searchoptions: { sopt: ["eq", "ne", "lt", "le", "gt", "ge"] }
}
}
});
(in the example I didn't included width in the template)
colModel: [
...
{ name: "tax", width: 52, template: "number" },
{ name: "amount", width: 75, template: "number" },
{ name: "total", width: 60, template: "number" },
....
]
See the pull request for more details.

As with any jQuery plugin, you can extend the plugin with $.extend() like this:
(function($) {
var extensionMethods = {
// ...
};
$.extend(true,$.jgrid, extensionMethods);
})(jQuery);

Related

javascript how to make spans table header?? lib ng2-smart-table

I use a ng2-smart-table lib.
And I set like this:
settings = {
hideSubHeader: true,
pager: { perPage: 26, display: false },
actions: false,
columns: {
NO: {
title: 'number',
},
name: {
title: 'name',
},
},
};
And I want to create new columns in 'name' header.
As per official docs, there is no such functionality, you need to manually set the configuration. or go for another smart table may be Primeng's table is best for your use case.
Refer here for Primeng Datatable -
https://www.primefaces.org/primeng/#/table/colgroup
Here you can easily use colspan and rowspan as per your requirements.

Binding datasource to Kendo Grid where some field may not be present in JSON

I have a Kendo Grid and the data is bound with results from a webApi. Below is a snapshot of the code. This is used to render the Kendo Grid. Now in the JSON result there could be cases where the field 'nominalVoltage' will not be there. In other words some results may return the field, some may not. In case the field is not returned the code fails. I will get error like field is undefined.
Can this be handled anyway while loading Kendo grid controls?
$scope.columns = [{
field: 'businessCode',
title: 'Business Code',
width: '120px',
}, {
field: 'nominalVoltage',
title: 'Nominal Voltage',
width: '120px'
}];
var options = {
dataSource: {
data: data
},
width: '100%',
resizable: true,
sortable: true,
scrollable: true,
reorderable: true,
dataBinding: function (e) {
var pageSizes = e.sender.dataSource.pageSize() || 20;
},
pageable: {
pageSize: pageSize,
pageSizes: [5, 10, 20, 50, 100, 200],
refresh: true
},
columns: $scope.columns
};
You could apply a conditional template attribute on the grid column which requires validation:
field: 'nominalVoltage',
title: 'Nominal Voltage',
width: '120px',
template: "#if(nominalVoltage) {#:nominalVoltage#} else{'Oops nothing found'}#"
Or the template as a function,
template: validateNominalVoltage
function validateNominalVoltage(dataItem) {
return dataItem.nominalVoltage ? dataItem.nominalVoltage : 'Oops nothing found';
}
Usually this method is used to modify how data is being displayed i.e. bolding content, using an external HTML template but in your case this will work fine for checking if the nominalVoltage attribute contains a value before displaying.
You can set a schema for your data.
schema: {
model: {
businessCode: { type: "string" },
nominalVoltage: { type: "number" },
}
}
You can define template like below
//field: 'nominalVoltage', // do not include it
template: function(data) {
return data.nominalVoltage ? data.nominalVoltage : "";
},
title: 'Nominal Voltage',
width: '120px'

jqGrid - how to delete row from local data?

I am really new to the jqGrid. I'm loading local file (I'm parsing csv file into json and then transfer the array to jqGrid). Table generated through jqGrid should allow user to modify, add and delete the data in the grid. I tried to resolve my problem using various answers from here like:
Adding new row to jqGrid using modal form on client only
There I have found the example made by Oleg for the 4.7 version of jqGrid and reproduced the same code for my purpose. The result was that I am able to delete row which I added after the grid initialisation but I am unable to delete any other row which was loaded from the array.
Another interesting thing is that I am able to modify the rows loaded from array, the only thing I cannot do with the grid is to delete rows loaded from array. I appreciate any advices.
Here is part of the code with jqGrid:
var delSettings = {
onclickSubmit: function () {
var $this = $(this), p = $this.jqGrid("getGridParam"), newPage = p.page;
if (p.lastpage > 1) {// on the multipage grid reload the grid
if (p.reccount === 1 && newPage === p.lastpage) {
// if after deliting there are no rows on the current page
// which is the last page of the grid
newPage--; // go to the previous page
}
// reload grid to make the row from the next page visable.
setTimeout(function () {
$this.trigger("reloadGrid", [{page: newPage}]);
}, 50);
}
return true;
}
};
$("#jqGrid").jqGrid({
datatype: "local",
data: results.data,
editurl: "clientArray",
colModel: [
{
label: 'Id',
name: 'Id',
width: 60,
editable: true,
key: true,
sorttype: 'number'
},
{
label: 'Company',
name: 'Company',
width: 90,
editoptions: {size: 40},
editable: true,
sorttype: 'string'
},
{
label: 'Address',
name: 'Address',
width: 100,
editoptions: {size: 40},
editable: true
},
{
label: 'City',
name: 'City',
width: 80,
editoptions: {size: 40},
editable: true
}
],
height: '100%',
viewrecords: true,
caption: "Baza klientów Klimatest",
pager: "#jqGridPager",
sortable: true,
ignoreCase: true,
cmTemplate: {editable: true, searchoptions: {clearSearch: true }},
rowNum: 5,
rowList: [5, 10, 20],
});
// toolbar searching
$('#jqGrid').jqGrid('filterToolbar', { defaultSearch: 'cn'});
$('#jqGrid').jqGrid('navGrid',"#jqGridPager",
{ edit: true, add: true, del: true, search: true, refresh: true, view: true},
// options for the Edit Dialog
{
editCaption: "The Edit Dialog",
recreateForm: true,
closeAfterEdit: true,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// options for the Add Dialog
{
closeAfterAdd: true,
recreateForm: true,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// options for the Delete Dialog
delSettings,
// options for the Search Dialog
{
},
// options for the View Dialog
{
});
// add first custom button
$('#jqGrid').navButtonAdd('#jqGridPager',
{
buttonicon: "ui-icon-calculator",
title: "Column chooser",
caption: "Columns",
position: "last",
onClickButton: function() {
// call the column chooser method
jQuery("#jqGrid").jqGrid('columnChooser');
}
});
EDIT
Data source is the result of parsed CSV file via Papaparse.js plugin (array of objects), which looks like this:
Id: "100,1"
Address: "Strefowa 8"
Company: "DSSE Sp. z o.o."
City: "Warsaw"
I edited the code just like Oleg suggested and I'm still able to delete only records which are added via interface of jqGrid.
I don't know if it may help, but when I click delete icon and confirm that I want to delete selected row, that row is no longer highlighted, but still visible. Thanks for feedback.
You have clear error in your code near // options for the View Dialog block. The View option should be included after delete and search options (see the documentation). So your current code don't use delSettings options.
I recommend you additionally to include test data in your next questions, because some problems exist only with some specific format of input data.
UPDATED: The problem is in the data which you use. The value for Id which you use contains comma ("100,1"). It's not allowed for jqGrid. First of all id in HTML should not use characters which have special meaning in CSS. The second problem: delGridRow method uses commas in separator to delete multiple rows at once. So the usage of id="100,1" will follows to attempt to delete tow rows: one row with id=100 and the second one with the id=1. By the way I'm developing now jqGrid in my fork of GitHub. I fixed many restrictions with the usage of special characters in ids. So you will be do able to use id="100,1" and successfully delete the rows if you would use jqGrid from my fork.
I recommend you to use underscore if you need to construct id which consist from multiple numbers: Id: "100_1" instead of Id: "100,1".

jquery grid not filled with JSon data

Hi I am not able to get the data from JSON loaded on to grid,
HEre is my code for the grid wich displays the stock prices for the stock for a user :
$(document).ready(function () {
// $("#jQGrid").html("<table id=\"list\"></table><div id=\"page\"></div>");
jQuery("#jqTable").jqGrid({
url:jqDataUrl,
datatype: "json",
mtype: "POST",
height: 250,
// Specify the column names
colNames: ["SYMBOL", "LAST", "CHANGE", "%CHANGE","HIGH/LOW"],
// Configure the columns
colModel: [
{ name: "SYMBOL", index: "SYMBOL", width: 200, align: "left" },
{ name: "LAST", index: "LAST", width: 200, align: "left" },
{ name: "CHANGE", index: "CHANGE", width: 200, align: "left" },
{ name: "%CHANGE", index: "%CHANGE", width: 200, align: "left"},
{ name: "HIGH/LOW", index: "HIGH/LOW", width: 200, align: "left"}
],
jsonReader : {
root: "rows",
page: "page",
total: "total",
records: "records",
cell: "cell",
id: "id",
},
multiselect: false,
// paging: true,
// rowNum:10,
// rowList:[10,20,30],
pager: $("#jqTablePager"),
loadonce:true,
caption: "WatchList"
}).navGrid('#jqTablePager',{edit:false,add:true,del:true});
}
});
But when i try and run the code i am not able to get the contents on to the table (but the grid loads with no content)
And My json is of the form :
{
total: "1",
page: "1",
records: "2",
rows :
[
{id:"1", cell:["cell11", "cell12", "cell13","cell13","cell13"]},
{id:"2", cell:["cell21", "cell22", "cell23","cell13","cell13"]}
]
}
Please help me solve the problem
UPDATE:
I discovered that if you do not put repeatitems:true option into json reader, jqGrid assumes that you are using json dot notation. When you put it into jsonReader, your data is properly loaded. Here is working example: http://jsfiddle.net/a5e5F/3/
Old version:
I played a lot with your jqgrid code, and it seems that there is a bug in this version of jqGrid, which causes your jsonReader not to work. It reads data directly, ignoring root element and assuming that your data is array of json objects in format
{propertyName1:'PropertyValue1', propertyName2:'PropertyValue2', ...}
You can see what I mean on http://jsfiddle.net/a5e5F/2/
If you replace data:rows with data:data (your format of data), it does not load data. Maybe you should try to change your json data to use real json format (with properties named as columns)?
I have been trying a ton of stuff, changing column names to check for issue in #Barmar's coment, which I also thought it is the cause.

jqGrid, couldn't get showlink formatter working

Hi I am trying to get showlink formatter working by following this document from trirand.
What I want to achieve is a hyperlink I can click for a edit view to update/edit records. But for some reason, the column are empty where I want show a hyperlink.
Here is my code snippets, and link is the last column:
<script type="text/javascript">
$(document).ready(function () {
$("#grid_products").jqGrid({
jsonReader: {
repeatitems: false,
id: 'Guid'
},
url: '/Product/jqgridJSON/',
datatype: 'json',
mtype: 'GET',
colNames: ['ProductCode', 'ProductDescription', 'DefaultSellPrice', 'LastCost', 'Edit'],
colModel: [
{ name: 'ProductCode', index: 'Productcode' },
{ name: 'ProductDescription', index: 'ProductDescription' },
{ name: 'DefaultSellPrice', formatter: 'currency', index: 'DefaultSellPrice' },
{ name: 'LastCost', formatter: 'currency', index: 'LastCost' },
{ name: 'MyLink',
edittype: 'select',
formatter: 'showlink',
formatoptions: { baseLinkUrl: '/Product/Update/', idName: 'Guid' }
},
],
pager: '#pager',
rowNum: 10,
rowList: [20, 50, 100, 200],
sortname: 'ProductCode',
sortorder: 'asc',
viewrecords: true,
width: 'auto',
height: 'auto',
caption: 'Products'
}).navGrid('#pager', { edit: true, add: false, del: false });
});
</script>
#{
ViewBag.Title = "JSONGrid";
}
<h2>JSONGrid</h2>
<table id="grid_products"></table>
<div id="pager"></div>
The formatter from jqGrid is working for currency, but for some reason, it just didn't shown for hyperlink.
Update:
Got it working by using custom formatter.
...
{ name: 'MyLink',
formatter: myLinkFormatter,
},
...
function myLinkFormatter (cellvalue, options, rowObjcet) {
return 'Edit this product';
}
I suppose that you fill no value in JSON input for the 'MyLink' column. Because of this the hyperlink is empty. If you want to place the link with any fixed text in column I would recommend you to use custom formatter. See the recent answer for an example.
One more possible solution way is to use formatter: 'showlink' and include jsonmap: function() { return "Edit"; } to the 'MyLink' column definition. In the case you will not need to include in the JSON data "MyLink":"Edit" for every row of data. It's important to understand that the trick works only in case of usage jsonReader: {repeatitems: false} (so it should work for your grid).
If you have another problem you should include in the text of your question the JSON data which you use.
Some small remarks to your current code:
the usage of edittype: 'select' together with formatter: 'showlink' has no sense. You should remove it if you will do use formatter: 'showlink'.
the parameter height: 'atuo' should be height: 'auto'.
pager: $('#pager') is better to replace to pager: '#pager'. If you use pager: $('#pager'), the jqGrid will replace it internally to pager: '#pager' and the object $('#pager') will be discarded.
If you use jsonReader: { id: 'Guid'} and you don't plan to show the guids to the user you can remove the 'Guid' column from the grid. The id (the Guid in your case) will be used to assign ids of <tr> elements (table rows) of the grid. So you don't need to hold the same information twice

Categories