Adding links to jQgrid and open in new window - json

I have this jqgrid definition and I'm trying to open the selected document in a new Window.
My final urls should like these:
http://localhost/XPagesSortableSearchResults.nsf/xPerson.xsp?documentId=9D93E80306A7AA88802572580072717A&action=openDocument
and also I need to generate this type of url:
http://localhost/XPagesSortableSearchResults.nsf/$$OpenDominoDocument.xsp?documentId=9D93E80306A7AA88802572580072717&action=openDocument
$().ready(function(){
jQuery("#list2").jqGrid({
url:'./xGrid7.xsp/peoplejson',
datatype: "json",
colNames:['InternetAddress','#','Name','OfficeCountry'],
colModel:[
{name:'InternetAddress',index:'InternetAddress', width:200},
{name:'#position',index:'#position', width:50,sorttype:'int'},
{name:'$17',index:'$17', width:200},
{name:'OfficeCountry',
width:200,
formatter:editLinkFmatter
// formatter:'showlink',
// formatoptions:{ baseLinkUrl:'xPerson.xsp',addParam: '&action=openDocument', idName:'documentId'}
}
],
jsonReader: {
repeatitems: false,
id: '#unid',
root: function (obj) {
if ($.isArray(obj)) {
return obj;
}
if ($.isArray(obj.items)) {
return obj.items;
}
return [];
},
page: function () { return 1; },
total: function () { return 1; },
records: function (obj) {
if ($.isArray(obj)) {
return obj.length;
}
if ($.isArray(obj.items)) {
return obj.items.length;
}
return 0;
}
},
caption: "JSON Example",
height: 500,
gridview: true,
loadonce: true,
ignoreCase: true,
rowNum: 50,
rowList: [50, 100, 500, 1000],
pager: '#pager2'
}).jqGrid('filterToolbar', {stringResult: true, defaultSearch: 'cn', searchOnEnter: false});
Note my Json object looks like this and I'm not using the documentId I need on my url as part of my ColModel; the value I need is #unid
[
{
"#entryid":"1-B933790B1DC265ED8025725800728CC5",
"#unid":"B933790B1DC265ED8025725800728CC5",
"#noteid":"1E76E",
"#position":"1",
"#read":true,
"#siblings":40000,
"#form":"Person",
"$17":"Aaron, Adam",
"InternetAddress":"consurgo#compleo.net",
"OfficeCountry":"Namibia"
},
{
"#entryid":"2-9D93E80306A7AA88802572580072717A",
"#unid":"9D93E80306A7AA88802572580072717A",
"#noteid":"19376",
"#position":"2",
"#read":true,
"#siblings":40000,
"#form":"Person",
"$17":"Aaron, Dave",
"InternetAddress":"gratia#incito.co.uk",
"OfficeCountry":"Brazil"
},
{
"#entryid":"3-FAFA753960DB587A80257258007287CF",
"#unid":"FAFA753960DB587A80257258007287CF",
"#noteid":"1D842",
"#position":"3",
"#read":true,
"#siblings":40000,
"#form":"Person",
"$17":"Aaron, Donnie",
"InternetAddress":"vociferor#nequities.net",
"OfficeCountry":"Algeria"
}
]
So far I make it work using:
{name:'OfficeCountry',
width:200,
formatter:'showlink',
formatoptions:{ baseLinkUrl:'xPerson.xsp',addParam: '&action=openDocument', idName:'documentId'}
}
but I need to open it in a new window
I also tried with formatter:editLinkFmatter
function editLinkFmatter(cellvalue, options, rowObject) {
return "<a href='./" + rowObject[2] + "' class='requestlink'>" + cellvalue + "</a>";
//return "<a href='./documentId=" + rowObject.#unid + "' >Click here</a>";
//return "<a href='./documentId=" + options.idName + "&action=OpenDocument'>" + cellvalue + "</a>";
}
and I can't use rowObject.#unid because the node name

It seems to me that you should just use target="_blank"attribute in the <a> (see here and here). The standard 'showlink' formatter supports target attribute.
As the alternative to the custom formatter you can use 'dynamicLink' formatter (see the answer). You can download the last version of jQuery.jqGrid.dynamicLink.js from here.
UPDATED: To assess the property with the name #unid you can use syntax rowObject["#unid"]. So the editLinkFmatter can be like
function editLinkFmatter(cellvalue, options, rowObject) {
return "<a href='?documentId=" + rowObject["#unid"] +
"&action=OpenDocument' class='requestlink'>" + cellvalue + "</a>";
}
or better like
function editLinkFmatter(cellvalue, options, rowObject) {
return "<a href='?" +
$.param({
documentId: rowObject["#unid"],
action: 'OpenDocument'
}) + "' class='requestlink'>" + cellvalue + "</a>";
}

Related

How to interpret htlm and css anotation in ajax data to pdfhtml5 datatable

I have a problem exporting with pdfhtml5. I have data on datatable with HTML and CSS style and want to visualize it on pdf or another plugin.
this is the variable exportOptions
var thisExportOptions = {
exportOptions: {
rows: function(idx, data, node) {
var checkedB = sontCoches(".dt-class-checkbox", "entireRow");
var dt = new $.fn.dataTable.Api('#datatable-configuration');
$(checkedB).each(function(i, v) {
dt.row(this).select();
});
var selected = dt.rows({ selected: true }).indexes().toArray();
if (selected.length === 0 || $.inArray(idx, selected) !== -1)
return true;
return false;
},
columns: ':visible'
}
};
and this for datatable id
var table = $('#datatable-configuration').DataTable({
"ajax": {
"url": "/backend/index.php",
"dataType": "json",
"type": "GET",
"data": {
"app": get ["app"],
"module": get ["module"],
"element": cElement,
"action": "serverside",
"actionParent": get ["action"],
//"get": get,
}
},
"buttons": [
$.extend(true, {}, thisExportOptions, { text: 'Imprimer', extend: 'print' }),
$.extend(true, {}, thisExportOptions, { text: 'PDF', extend: 'pdfHtml5' }),
{ extend: 'colvis', text: 'Export colonnes', className: 'btn-primary', columns: ":not(.notConcernedByColvis)" }
],
"fnStateLoad": function(oSettings) {
return JSON.parse(localStorage.getItem('dataTableStore'));
},
"stateSaveParams": function(settings, data) {
data.columns.forEach(function(column) {
delete column.visible;
});
}
)}
Php code
$datas[$key]['nom'] = "<span class='font-weight-bold text-success'>" . $brute->raison_sociale . "</span>";
$datas[$key]['nom'] .= (!empty($brute->rcs_siret)) ? "<br /><small><span class='font-weight-bold'>RCS : </span><span class='right'>" . $brute->rcs_siret . "</span></small>" : "";
$datas[$key]['autres'] = '';
And the pdf file is like this
Pdf export with no css and HTML no interpreted
Finally I found WkHtmlToPdf it can convert HTML page to PDF file.
It's very helpfull and free, PHP WkHtmlToPdf provides a simple and clean interface to ease PDF and image creation when you want only use free solution on your project.
For more information : https://github.com/mikehaertl/phpwkhtmltopdf

Any search result returned due to a free-text search should show preview text under each row in the results tables

I am applying filter on columns in the datatable as well as on the attributes that are not in the datatable but are in present in the database of the object. The filters are working fine and I am getting the output wanted. However on the text search I want to preview the text found that is not part of the attributes in the datatable under the row (refer to the image below for better understanding of the scenario).
I have tried dynamically adding a row but it just reloads the page and shows me the same data i got from the ajax request.
var counter = 1;
$('#addRow').on('click', function () {
datatable.row.add([
counter + '.1',
counter + '.2',
counter + '.3',
counter + '.4',
counter + '.5'
]).draw();
counter++;
});
here's the code of Datatable that handles the ajax request and renders the data
let datatable = companytable.DataTable({
lengthMenu: [[10, 20, 30, -1], [10, 20, 30, "All"]],
ajax: {
url: '/api/company/get?' + "&statusFilter=" + statusFilter + "&nameFilter=" + nameFilter
+ "&isrOfficeSelected=" + isrOfficeSelected + "&industrySelected=" + industrySelected
+ "&companyTypeSelected=" + companyTypeSelected
+ "&usOfficeSelected=" + usOfficeSelected
+ "&usOfficeStateSelected=" + usOfficeStateSelected
+ "&targetMarketSelected=" + targetMarketSelected
+ "&financingStageSelected=" + financingStageSelected
+ "&officeSizeSelected=" + officeSizeSelected
+ "&tamidReferralSelected=" + tamidReferralSelected
+ "&ratingLow=" + ratingLow + "&ratingHigh=" + ratingHigh
+ "&paidInternFrom=" + paidInternFrom + "&paidInternTo=" + paidInternTo
+ "&unpaidInternFrom=" + unpaidInternFrom + "&unpaidInternTo=" + unpaidInternTo
+ "&activeInternFrom=" + activeInternFrom + "&activeInternTo=" + activeInternTo
,
type: "GET",
},
processing: true,
serverSide: true,
language: {
processing: "Loading...",
paginate: {
previous: "<",
next: ">",
first: "<<",
last: ">>"
},
lengthMenu: "_MENU_"
},
columns: [
{
data: "CompanyName",
name: "CompanyName",
render: function (data, type, row) {
if (row.CompanyName !== '') {
return $('<span />')
.append($('<a />')
.prop('href', '/Consulting/Admin/Company?id=' + row.ID).text(row.CompanyName)).html();
}
return "";
}
},
{
data: 'Department',
name: "Department",
render: function (data, type, row) {
return $("<span/>").text(row.Department).html();
}
},
{
data: 'ContactName',
name: "ContactName",
render: function (data, type, row) {
return $("<span/>").text(row.FirstName + " " + row.LastName).html();
}
},
{
data: 'Email',
name: "Email",
render: function (data, type, row) {
return $("<span/>").text(row.Email).html();
}
},
{
data: "CurrentRating",
name: "CurrentRating",
render: function (data, type, row) {
let rating = $('<span />');
rating.append($('<span class="hidden" />').text(row.CurrentRating));
for (var i = 0; i < 5; i++) {
rating.append($('<i ></i>').addClass(i < parseInt(row.CurrentRating) ? 'fa fa-star text-primary' : 'fa fa-star-o text-muted'))
}
return rating.html();
}
},
],
dom: '<"top">rt<"bottom"pl><"clear">',
pagingType: "full_numbers",
});
Image Reference of the desired output

Ajax Response Capitalizations Rules

A was using DataTables plugin, and when displaying my columns I needed to put the first letter to LowerCase for it to recognize the property/object, e.g:
// Object name is actually: EngineeringChange.Responsible
{
title: "Responsible",
data: "engineeringChange.responsible",
className: "columnName columnHeader",
},
I just assumed the first letter would always be capitalized to LowerCase. I tried creating a new property inside EngineeringChange named ECRNumber, so I tried:
{
title: "ECR Number",
data: "engineeringChange.eCRNumber",
className: "columnName columnHeader",
},
Isn't recognized as a parameter... After a bit of searching I find out the Json response I get on AJAX it's called ecrNumber. So now I'm actually lost on which are the rules that are automatically applied to the Json Response. How does it turn ecr to LowerCase and Number to UpperCase (the N)??
Edit
Sry, can´t think of any easy way to exactly reproduce my problem on a demo
TableDesign/Creation
table = $('#tblEntries2').DataTable({
order: [[0, 'desc']],
deferRender: true,
ajax: {
url: '#Url.Action("GetEntries", "AlteracaoEngenharia")',
method: 'GET',
dataSrc: '',
beforeSend: function () {
onBegin();
$content.hide();
$loader.show();
},
complete: function (jsonResponse) {
console.log(jsonResponse);
onComplete();
$loader.hide();
$content.fadeIn();
$('#ExcelExport').show();
table.column(5).visible(false);
table.column(6).visible(false);
table.column(7).visible(false);
table.column(9).visible(false);
table.column(10).visible(false);
table.column(11).visible(false);
}
},
dom: "<'row'<'col-2'l><'col-7 text-center'B><'col-3'f>>" +
"<'row'<'col-12'tr>>" +
"<'row'<'col-5'i><'col-7'p>>",
lengthMenu: [
[10, 25, 50, 100, -1],
['10', '25', '50', '100', 'Todos'],
],
columns: [
{
title: "Id (yr-id)",
data: "creationYear",
className: "columnNumber columnHeader",
},
{
title: "ECR Number",
data: "engineeringChange.ecrNumber",
className: "columnNumber columnHeader",
},
{
title: "Criador Alteração de Engenharia",
data: "engineeringChange.responsible",
className: "columnName columnHeader",
},
...
Handler
public IActionResult GetEntries()
{
GetDataEntries();
int count = 0;
int currentYear = 0;
foreach (var entry in EntriesList)
{
EngineeringChangesListViewModel h = new EngineeringChangesListViewModel
{
EngineeringChange = entry
};
if (currentYear != entry.DataCriacao.Year)
{
count = 1;
currentYear = entry.DataCriacao.Year;
}
else
{
count++;
}
h.DeadLine = entry.FinishedGood.Week + " - " + entry.DataCriacao.Year.ToString();
if (entry.OldPart == null)
{
h.EngineeringChange.OldPart = new Part();
}
if (entry.NewPart == null)
{
h.EngineeringChange.NewPart = new Part();
}
if (entry.FinishedGood == null)
{
h.EngineeringChange.FinishedGood = new FinishedGood();
}
if (entry.OldPart != null && entry.OldPart.CDP.HasValue)
h.OldPartValue = entry.OldPart.CDP * entry.OldPart.Stock;
if (entry.NewPart != null && entry.NewPart.CDP.HasValue)
h.NewPartValue = entry.NewPart.CDP * entry.NewPart.Stock;
h.EngineeringChange.ECRNumber = entry.ECRNumber;
//toString("D4") padds the number to always be 4 digits
h.CreationYear = entry.DataCriacao.Year.ToString() + "_" + count.ToString("D4");
h.IdYear = count;
EntriesListaViewModel.Add(h);
}
var errorsJson = JsonConvert.SerializeObject(EntriesListaViewModel);
Console.WriteLine(errorsJson);
return new JsonResult(EntriesListaViewModel);
}
HANDLER OUTPUT
[{"CreationYear":"2021_0001","IdYear":1,"OldPartValue":null,"NewPartValue":2061.09155,"DeadLine":"15 - 2021","EngineeringChange":{"Id":8,"DataCriacao":"2021-03-11T16:15:24.6630956","Responsible":"José António","ECRNumber":"X1232","State":"Aberto","Comment":"Teste","UserId":1,"User":null,"Component":null,"FinishedGood":{"Id":31,"Week":15,"EngineeringChangeId":8},"OldPart":{"Id":5,"Reference":"FS12848AC","Stock":null,"CDP":1.43584776,"LastExpired":null},"NewPart":{"Id":6,"Reference":"FS12848AD","Stock":1650,"CDP":1.24914646,"LastExpired":"2021-03-11T00:00:00"},"Transformation":{"Id":188,"Possible":true,"Cost":1090.0,"WillBeTransformed":true,"TransformationDate":"2021-03-13T08:48:00","Responsible":"Miguel","EngineeringChangeId":8}}},]
PAGE/AJAX OUTPUT outputs are created by console.log() and Console.WriteLine() displayed above.
ECRNumber gets named to ecrNumber...

Kendo Grid Drop-Down column with conditional formatting

I have a grid I'm working on, and some of the columns are Boolean (true/false). I want them to display as "Yes/No" in the column. I also am using a drop-down to change the value. The issue I am having is that once I select the value form the drop-down, it doesn't display the new value when I leave the line. But only if I'm going from "no" to "yes". I think it's something to do with the interaction between my template and the drop-down? That the value isn't getting set to "yes" from the drop down for the template, so it'd falling into the "no" logic.
Here is my data for the drop-down:
indData = [
{ Text: "Yes", boolValue: "true" },
{ Text: "No", boolValue: "false" }
];
And my definition for that column:
Copy code
{
field: "FreeAndReducedInd", width: "150px",
editor: indDropDownEditor,
title: "Free and Reduced",
template: ("# if (FreeAndReducedInd == true) { #" + "Yes" + "# } else { #" + "No" + "#}#")
},
And the editor code:
Copy code
function indDropDownEditor(container, options) {
$('<input data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
dataTextField: "Text",
dataValueField: "boolValue",
dataSource: indData
});
};
What do I have wrong?
thanks
Lisa
Update - I got an answer from Kendo, they suggested I add a Custom Binder and that seems to be working.
kendo.data.binders.widget.boolValue = kendo.data.Binder.extend({
init: function (widget, bindings, options) {
kendo.data.Binder.fn.init.call(this, widget.element[0], bindings, options);
this.widget = widget;
this._change = $.proxy(this.change, this);
this.widget.bind("change", this._change);
},
refresh: function () {
var value = this.bindings.boolValue.get();
this.widget.value(value.toString());
},
change: function () {
var value = this.widget.value();
this.bindings.boolValue.set(value === "true");
},
destroy: function () {
this.widget.unbind("change", this._change);
}
});
I also modified my editor:
function indDropDownEditor(container, options) {
$('<input data-bind="boolValue:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
dataTextField: "Text",
dataValueField: "boolValue",
dataSource: [
{ Text: "Yes", boolValue: "true" },
{ Text: "No", boolValue: "false" }
]
});
};
It would be better if you could give us the full code. Its easier to check locally before giving any solution. But try using the following in template. If it doesn't help please update your post with full code so I can recheck. Thanks.
template: "<td role='gridcell'> #= FreeAndReducedInd == true ? 'Yes' : 'No' # </td>"

how to create a javascript function with parameters in another javascript file to use within another javascript?

hey, good day. im creating a program that would load a data from a server into a jqgrid. what im trying to do now is create a function from a separate javascript file and just use that function in my other javascript-jqgrid-load-data. here's my code in javascript:
$("#tbl").jqGrid({
url: '',
datatype: 'local',
jsonReader : {
root: function(obj) {
//some codes here
return root;
},
page: "page",
total: "pageCount",
records: "rows",
repeatitems:false,
id: "0"
},
serializeGridData: function(postData) {
var jsonParams = {
.
.//some codes here
.
'sort_fields': postData.sidx
};
if (postData.sord == 'desc')
{
..//some codes
}
else
{
...//some codes
}
jpar = jsonParams;
return 'json=' + jsonParams;
},
loadError: function(xhr, msg, e) {
showMessage('msg error');
},
colNames:['ID',...'Type'],
colModel:[
...//col model
],
rowNum:5,
.
.
.//some codes here
loadonce:false,
caption: "Main Account Group"
});
i want to separate the code:
jsonReader : {
root: function(obj) {
//some codes here
return root;
},
page: "page",
total: "pageCount",
records: "rows",
repeatitems:false,
id: "0"
},
and this:
serializeGridData: function(postData) {
var jsonParams = {
.
.//some codes here
.
'sort_fields': postData.sidx
};
if (postData.sord == 'desc')
{
..//some codes
}
else
{
...//some codes
}
jpar = jsonParams;
return 'json=' + jsonParams;
},
loadError: function(xhr, msg, e) {
showMessage('msg error');
},
I wrote my answer your your next question so that it answer on both from your question. The main idea is that you can either use global functions or better redefine jqGrid defaults with respect of
jQuery.extend(jQuery.jgrid.defaults, {/*your changes to the defaults*/});