How to access row and column data on click of an icon in ColumnListItem - json

I have a JS view in which I am creating a sap.m.Table. It's "columns" are bound to a JSONModel. It's "items" are bound to ODataModel. I want to access the row data and the column name when I click on an Icon contained in the ColumnListItem.
View code:
createContent : function(oController) {
var oTable = new sap.m.Table("table1", {
width: "auto",
noDataText: "Please add rows to be displayed!"
}).addStyleClass("sapUiResponsiveMargin");
oTable.bindAggregation("columns", "Periods>/periods", function(sId, oContext) {
var sColumnId = oContext.getObject().period;
return new sap.m.Column({
hAlign: "Center",
vAlign: "Middle",
header: new sap.m.Text({
text: sColumnId
})
});
});
oTable.bindItems("zStatus>/StatusSet", function(sId, oContext) {
var row = new sap.m.ColumnListItem(sId, {
type : "Inactive",
cells: [
new sap.ui.core.Icon({
src: "sap-icon://delete",
hoverColor: "red",
activeColor: "red",
press: [oController.onDeleteIconPress, oController]
}),
new sap.m.Text({
text: "{zStatus>Description}"
}),
new sap.ui.core.Icon(sId, {
src: {
path: "zStatus>Status1",
formatter: function(status) {
switch(status) {
case "R":
return "sap-icon://sys-cancel";
case "G":
return "sap-icon://sys-enter";
case "Y":
return "sap-icon://notification";
default:
return "sap-icon://sys-help";
}
}
},
size: "1.5em",
press: [oController.onStatusIconPress, oController]
}) ]
});
return oTable;
}
In my controller I create an array, then a JSON model "Periods" from it and set it to this view. Odata model "zStatus" is defined in manifest file.
Controller code:
onInit : function() {
// array aPeriods is populated first then
var oPeriodsModel = new sap.ui.model.json.JSONModel();
oPeriodsModel.setData({
periods : aPeriods
});
this.getView().setModel(oPeriodsModel, "Periods");
},
onStatusIconPress : function(oEvent) {
// I can get the row data on icon press
// Problem 2: but how do I get the column name?
// I wanted to attach the column name to icon as customData but I could
// not access model attached to columns inside bindItems method
}

I managed to solve it myself.
Created an array in createContent. Filled it with column IDs in bindAggregation of columns and then used this array in bindItems method.
Then I can pass customData to icons.
Here is the code -
createContent : function(oController) {
var aColumns = []; // array to store column ids
var columnIndex = 0; // index to track
//more code
// create table oTable
oTable.bindAggregation("columns", "/columns", function(sId, oContext) {
var sColumnId = oContext.getObject().period;
if (sColumnId === "DeleteIcon") {
// this is always my first column
columnIndex = 0;
return new sap.m.Column({
hlign : "Begin",
vAlign : "Middle",
width : "2em",
header : new sap.m.Text({
text : ""
})
});
} else {
// add column ids to array
aColumns[columnIndex++] = sColumnId;
return new sap.m.Column({
hlign : "Center",
vAlign : "Middle",
header : new sap.m.Text({
text : sColumnId
})
});
}
});
oTable.bindItems("/rows", function(sId, oContext) {
var row = new sap.m.ColumnListItem({
new sap.m.Text({
text: "{Name}"
}),
new sap.ui.core.Icon(sId, {
src: "sap-icon://sys-help"
size: "1.5em",
press: [oController.onStatusIconPress, oController],
customData : [
// use column ids here
new sap.ui.core.CustomData({key: "column", value: aColumns[0]})
]
}),
});
return row;
}
}

Related

JQGgrid- How to generate a pdf / excel file from the grid data

I have the following JQGrid table, which is being generated from JSON data. I want to be able to generate/export or create a pdf file based on the table data state that is view able. I am using JSON , Jqgrid and Javascript
How do I generate a pdf file from the data ?
Here My FIDDLE
JS CODE
$(document).ready(function() {
var jsonData = {
"Name": "Julie Brown",
"Account": "C0010",
"LoanApproved": "12/5/2015",
"LastActivity": "4/1/2016",
"PledgedPortfolio": "4012214.00875",
"MaxApprovedLoanAmt": "2050877.824375",
"LoanBalance": "1849000",
"AvailableCredit": "201877.824375",
"Aging": "3",
"Brokerage": "My Broker",
"Contact": "Robert L. Johnson",
"ContactPhone": "(212) 902-3614",
"RiskCategory": "Yellow",
"rows": [{
"ClientID": "C0010",
"Symbol": "WEC",
"Description": "Western Electric Co",
"ShareQuantity": "20638",
"SharePrice": "21.12",
"TotalValue": "435874.56",
"LTVCategory": "Equities",
"LTVRatio": "50%",
"MaxLoanAmt": "217937.28"
}, {
"ClientID": "C0010",
"Symbol": "BBB",
"Description": "Bins Breakers and Boxes",
"ShareQuantity": "9623",
"SharePrice": "74.29125",
"TotalValue": "714904.69875",
"LTVCategory": "Equities",
"LTVRatio": "50%",
"MaxLoanAmt": "357452.349375"
}, {
"ClientID": "C0010",
"Symbol": "GPSC",
"Description": "Great Plains Small Cap Stock",
"ShareQuantity": "49612",
"SharePrice": "14.24",
"TotalValue": "706474.88",
"LTVCategory": "Mutual Funds - Small Cap",
"LTVRatio": "40%",
"MaxLoanAmt": "282589.952"
}]
},
mmddyyyy = "";
/*********************************************************************/
$("#output").jqGrid({
url: "/echo/json/",
mtype: "POST",
datatype: "json",
postData: {
json: JSON.stringify(jsonData)
},
colModel: [
/** { name: 'ClientID', label:'ClientID',width: 80, key: true },****/
{
name: 'Symbol',
width: 65
}, {
name: 'Description',
width: 165
}, {
name: 'ShareQuantity',
align: 'right',
width: 85,
classes: "hidden-xs", labelClasses: "hidden-xs",
formatter: 'currency',
formatoptions: {
prefix: " ",
suffix: " "
}
}, {
name: 'SharePrice',
label: 'Share Price',
align: 'right',
width: 100,
classes: "hidden-xs", labelClasses: "hidden-xs",
template: "number",
formatoptions: {
prefix: " $",
decimalPlaces: 4
}
},
/*{ label: 'Value1',
name: 'Value1',
width: 80,
sorttype: 'number',
formatter: 'number',
align: 'right'
}, */
{
name: 'TotalValue',
label: 'Total Value',
width: 160,
sorttype: 'number',
align: "right",
search: false,
formatter: 'currency',
formatoptions: {
prefix: " $",
suffix: " "
}
}, {
name: 'LTVRatio',
label: 'LTV Ratio',
width: 70,
sorttype: 'number',
align: "right",
formatter: 'percentage',
formatoptions: {
prefix: " ",
suffix: " "
}
}, {
name: 'LTVCategory',
label: 'LTV Category',
classes: "hidden-xs", labelClasses: "hidden-xs",
width: 120,
width: 165
},
{
name: 'MaxLoanAmt',
label: 'MaxLoanAmount',
width: 165,
sorttype: 'number',
align: "right",
search: false,
formatter: 'currency',
formatoptions: {
prefix: " $",
suffix: " "
}
}
],
additionalProperties: ["Symbol", "Description"],
subGrid: true,
subGridRowExpanded: function (subgridDivId, rowid) {
var item = $(this).jqGrid("getLocalRow", rowid);
$("#" + $.jgrid.jqID(subgridDivId)).html("Symbol: <em>" + item.Symbol +
"</em><br/>Description: <em>" + item.Description + "</em>");
},
beforeProcessing: function (data) {
var symbolsMap = {}, symbolsValues = ":All", rows = data.rows, i, symbol;
for (i = 0; i < rows.length; i++) {
symbol = rows[i].Symbol;
if (!symbolsMap.hasOwnProperty(symbol)) {
symbolsMap[symbol] = 1;
symbolsValues += ";" + symbol + ":" + symbol;
}
}
$(this).jqGrid("setColProp", 'Symbol', {
stype: "select",
searchoptions: {
value: symbolsValues
}
}).jqGrid('destroyFilterToolbar')
.jqGrid('filterToolbar', {
stringResult: true,
searchOnEnter: false,
defaultSearch : "cn"
});
},
/*beforeProcessing: function (data) {
var item, i, n = data.length;
for (i = 0; i < n; i++) {
item = data[i];
item.Quantity = parseFloat($.trim(item.Quantity).replace(",", ""));
item.LTVRatio = parseFloat($.trim(item.LTVRatio *10000).replace(",", ""));
item.Value = parseFloat($.trim(item.Value).replace(",", ""));
item.Num1 = parseInt($.trim(item.Num1).replace(",", ""), 10);
item.Num2 = parseInt($.trim(item.Num2).replace(",", ""), 10);
}
}, */
iconSet: "fontAwesome",
loadonce: true,
rownumbers: true,
cmTemplate: {
autoResizable: true,
editable: true
},
autoResizing: {
compact: true
},
autowidth: true,
height: 'auto',
forceClientSorting: true,
sortname: "Symbol",
footerrow: true,
caption: "<b>Collateral Value</b> <span class='pull-right' style='margin-right:20px;'>Valuation as of: " + mmddyyyy + "</span>",
loadComplete: function() {
var $self = $(this),
sum = $self.jqGrid("getCol", "Price", false, "sum"),
sum1 = $self.jqGrid("getCol", "MaxLoanAmt", false, "sum");
//ltvratio = $self.jqGrid("getCol","LTVRatio:addas", "Aved Loan Amount");
$self.jqGrid("footerData", "set", {
LTVCategory: "Max Approved Loan Amount:",
Price: sum,
MaxLoanAmt: sum1
});
}
});
$("#output").jqGrid('filterToolbar', {stringResult: true, searchOnEnter: false, defaultSearch : "cn"});
$(window).on("resize", function () {
var newWidth = $("#output").closest(".ui-jqgrid").parent().width();
$("#output").jqGrid("setGridWidth", newWidth, true);
}).triggerHandle("resize");
});
There is no build in method to export jqgrid data to pdf. You have to use third party tools( I personally like iTextSharp which can be downloaded from Here . You have to create action method for printing the grid data in your controller.
Here is also another one example one guy made.
Here is also another example in trirand. If you see the source code they are using iTextHsarp.
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using JQGridMVCExamples.Models;
using Trirand.Web.Mvc;
using System.IO;
//
// For PDF export we are using the free open-source iTextSharp library.
//
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Data;
namespace JQGridMVCExamples.Controllers.Grid
{
public partial class GridController : Controller
{
// This is the default action for the View. Use it to setup your grid Model.
public ActionResult ExportPDF()
{
// Get the model (setup) of the grid defined in the /Models folder.
var gridModel = new OrdersJqGridModel();
var ordersGrid = gridModel.OrdersGrid;
// Setting the DataUrl to an action (method) in the controller is required.
// This action will return the data needed by the grid
ordersGrid.DataUrl = Url.Action("PDFGrid_DataRequested");
// customize the default Orders grid model with custom settings
// NOTE: you need to call this method in the action that fetches the data as well,
// so that the models match
SetPDFExportGrid(ordersGrid);
// Pass the custmomized grid model to the View
return View(gridModel);
}
// This method is called when the grid requests data
public JsonResult PDFGrid_DataRequested()
{
// Get both the grid Model and the data Model
// The data model in our case is an autogenerated linq2sql database based on Northwind.
var gridModel = new OrdersJqGridModel();
var northWindModel = new NorthwindDataContext();
// customize the default Orders grid model with our custom settings
SetPDFExportGrid(gridModel.OrdersGrid);
// Save the current grid state in Session
// We will later need it for PDF Export
JQGridState gridState = gridModel.OrdersGrid.GetState();
Session["gridState"] = gridState;
// return the result of the DataBind method, passing the datasource as a parameter
// jqGrid for ASP.NET MVC automatically takes care of paging, sorting, filtering/searching, etc
return gridModel.OrdersGrid.DataBind(northWindModel.Orders);
}
public JsonResult PDFExport_AutoCompleteShipName(string term)
{
var northWindModel = new NorthwindDataContext();
JQAutoComplete autoComplete = new JQAutoComplete();
autoComplete.DataField = "ShipName";
autoComplete.AutoCompleteMode = AutoCompleteMode.BeginsWith;
autoComplete.DataSource = from o in northWindModel.Orders
select o;
return autoComplete.DataBind();
}
private void SetPDFExportGrid(JQGrid ordersGrid)
{
// show the search toolbar
ordersGrid.ToolBarSettings.ShowSearchToolBar = true;
ordersGrid.ToolBarSettings.ShowSearchButton = true;
var orderDateColumn = ordersGrid.Columns.Find(c => c.DataField == "OrderDate");
orderDateColumn.DataFormatString = "{0:yyyy/MM/dd}";
orderDateColumn.SearchType = SearchType.DatePicker;
orderDateColumn.DataType = typeof(DateTime);
orderDateColumn.SearchControlID = "DatePicker";
orderDateColumn.SearchToolBarOperation = SearchOperation.IsEqualTo;
var shipNameColumn = ordersGrid.Columns.Find(c => c.DataField == "ShipName");
shipNameColumn.SearchType = SearchType.AutoComplete;
shipNameColumn.DataType = typeof(string);
shipNameColumn.SearchControlID = "AutoComplete";
shipNameColumn.SearchToolBarOperation = SearchOperation.Contains;
var orderIDColumns = ordersGrid.Columns.Find(c => c.DataField == "OrderID");
orderIDColumns.Searchable = true;
orderIDColumns.DataType = typeof(int);
orderIDColumns.SearchToolBarOperation = SearchOperation.IsEqualTo;
SetPDFCustomerIDSearchDropDown(ordersGrid);
SetPDFFreightSearchDropDown(ordersGrid);
}
private void SetPDFCustomerIDSearchDropDown(JQGrid ordersGrid)
{
// setup the grid search criteria for the columns
JQGridColumn customersColumn = ordersGrid.Columns.Find(c => c.DataField == "CustomerID");
customersColumn.Searchable = true;
// DataType must be set in order to use searching
customersColumn.DataType = typeof(string);
customersColumn.SearchToolBarOperation = SearchOperation.IsEqualTo;
customersColumn.SearchType = SearchType.DropDown;
// Populate the search dropdown only on initial request, in order to optimize performance
if (ordersGrid.AjaxCallBackMode == AjaxCallBackMode.RequestData)
{
var northWindModel = new NorthwindDataContext();
var searchList = from customers in northWindModel.Customers
select new SelectListItem
{
Text = customers.CustomerID,
Value = customers.CustomerID
};
customersColumn.SearchList = searchList.ToList<SelectListItem>();
customersColumn.SearchList.Insert(0, new SelectListItem { Text = "All", Value = "" });
}
}
private void SetPDFFreightSearchDropDown(JQGrid ordersGrid)
{
// setup the grid search criteria for the columns
JQGridColumn freightColumn = ordersGrid.Columns.Find(c => c.DataField == "Freight");
freightColumn.Searchable = true;
// DataType must be set in order to use searching
freightColumn.DataType = typeof(decimal);
freightColumn.SearchToolBarOperation = SearchOperation.IsGreaterOrEqualTo;
freightColumn.SearchType = SearchType.DropDown;
// Populate the search dropdown only on initial request, in order to optimize performance
if (ordersGrid.AjaxCallBackMode == AjaxCallBackMode.RequestData)
{
List<SelectListItem> searchList = new List<SelectListItem>();
searchList.Add(new SelectListItem { Text = "> 10", Value = "10" });
searchList.Add(new SelectListItem { Text = "> 30", Value = "30" });
searchList.Add(new SelectListItem { Text = "> 50", Value = "50" });
searchList.Add(new SelectListItem { Text = "> 100", Value = "100" });
freightColumn.SearchList = searchList.ToList<SelectListItem>();
freightColumn.SearchList.Insert(0, new SelectListItem { Text = "All", Value = "" });
}
}
public ActionResult ExportToPDF(string exportType)
{
var gridModel = new OrdersJqGridModel();
var northWindModel = new NorthwindDataContext();
var grid = gridModel.OrdersGrid;
// Get the last grid state the we saved before in Session in the DataRequested action
JQGridState gridState = Session["GridState"] as JQGridState;
// Need to set grid options again
SetExportGrid(grid);
if (String.IsNullOrEmpty(exportType))
exportType = "1";
DataTable exportData;
switch (exportType)
{
case "1":
grid.ExportSettings.ExportDataRange = ExportDataRange.All;
exportData = grid.GetExportData(northWindModel.Orders);
ExportToPDF(exportData);
break;
case "2":
grid.ExportSettings.ExportDataRange = ExportDataRange.Filtered;
exportData = grid.GetExportData(northWindModel.Orders, gridState);
ExportToPDF(exportData);
break;
case "3":
grid.ExportSettings.ExportDataRange = ExportDataRange.FilteredAndPaged;
exportData = grid.GetExportData(northWindModel.Orders, gridState);
ExportToPDF(exportData);
break;
}
return View();
}
private void ExportToPDF(DataTable dt)
{
//
// For PDF export we are using the free open-source iTextSharp library.
//
Document pdfDoc = new Document();
MemoryStream pdfStream = new MemoryStream();
PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, pdfStream);
pdfDoc.Open();//Open Document to write
pdfDoc.NewPage();
Font font8 = FontFactory.GetFont("ARIAL", 7);
PdfPTable PdfTable = new PdfPTable(dt.Columns.Count);
PdfPCell PdfPCell = null;
//Add Header of the pdf table
for (int column = 0; column < dt.Columns.Count; column++)
{
PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Columns[column].Caption, font8)));
PdfTable.AddCell(PdfPCell);
}
//How add the data from datatable to pdf table
for (int rows = 0; rows < dt.Rows.Count; rows++)
{
for (int column = 0; column < dt.Columns.Count; column++)
{
PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8)));
PdfTable.AddCell(PdfPCell);
}
}
PdfTable.SpacingBefore = 15f; // Give some space after the text or it may overlap the table
pdfDoc.Add(PdfTable); // add pdf table to the document
pdfDoc.Close();
pdfWriter.Close();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=gridexport.pdf");
Response.BinaryWrite(pdfStream.ToArray());
Response.End();
}
}
}

50053 incomplete dimension binding

Hello guys i have a problem with displaying my pie chart, when i try to add more data into the pie chart this error occurs, i need your expertise on this matter
this is my controller code. and the error message is
[50053] - Incomplete dimensions binding
onInit: function() {
this._setupSelectionList();
// 2.Create a JSON Model and set the data
var oModel = new sap.ui.model.json.JSONModel("http://lssinh000.sin3.sap.corp:8000/SAP_LE/lionExpress/Volunteer/Services/request.xsjs");
var oVizFrame = this.getView().byId("idpiechart");
// 3. Create Viz dataset to feed to the data to the graph
var oDataset = new sap.viz.ui5.data.FlattenedDataset({
dimensions : [{
name : 'Status',
value : "{Status}",
name : 'StartDate',
value : '{StartDate}'
}],
measures : [{
name : 'reqID',
value : '{reqID}',
},],
data : {
path : "/Status"
}
});
oVizFrame.setDataset(oDataset);
oVizFrame.setModel(oModel);
// 4.Set Viz properties
oVizFrame.setVizProperties({
title:{
text : "Delivery Summary"
},
plotArea: {
colorPalette : d3.scale.category20().range(),
drawingEffect: "glossy"
}});
var feedSize = new sap.viz.ui5.controls.common.feeds.FeedItem({
'uid': "size",
'type': "Measure",
'values': ["reqID"]
}),
feedColor = new sap.viz.ui5.controls.common.feeds.FeedItem({
'uid': "color",
'type': "Dimension",
'values': ["Status"]
}),
feedValue = new sap.viz.ui5.controls.common.feeds.FeedItem({
'uid': "value",
'type': "Dimension",
'values': ["StartDate"]
});
oVizFrame.addFeed(feedSize);
oVizFrame.addFeed(feedColor);
oVizFrame.addFeed(feedValue);
//this.getView().byId("idPopOver").connect(oVizFrame.getVizUid());
},
In the dataset, the name attribute has to be same as in the values arrays of the feeds.

sapui5/openui5 TreeTable with custom control column throwing duplicate id error when expanding a node

I have a sap.ui.table.TreeTable with several columns, one of which contains a custom control defined as a template for the column.
The TreeTable renders correctly, and the column with the custom control also renders and functions correctly ... that is until I expand an unexpanded node.
When I expand a node the Renderer throws an error
Error: adding element with duplicate id '__link0-col1-row0',
which is the column associated with the custom control.
I can workaround the problem by adding attachToggleOpenState event handler which destroys this columns template and adds it again. Expensive but it works!
this.oTable = new sap.ui.table.TreeTable("myTable", {
columns : [ new sap.ui.table.Column( {
label : "Query",
template : new sparqlish.control.queryClause({
clausePath : {
path : "viewModel>path"
}
}),
visible : true,
width : "500px"
}), ],
}).attachToggleOpenState(function(oEvent) {
// TODO workaround as expanding Tree causes duplicate id
var queryColumn = oEvent.getSource().getColumns()[0];
queryColumn.destroyTemplate();
queryColumn.setTemplate(new sparqlish.control.queryClause({
clausePath : {
path : "viewModel>path"
}
}))
});
sparqlish.control.queryClause is the custom control.
I am using openui5 version 1.28.15
Any other, less expensive, suggestions?
The custom control takes this form, however this control invokes other controls and so on.
jQuery.sap.require("sparqlish.control.conceptClause");
jQuery.sap.require("sparqlish.control.propertyClause");
jQuery.sap.require("sparqlish.control.conjunctionPropertyClause");
sap.ui.core.Control.extend("sparqlish.control.queryClause", {
metadata : {
properties : {
clausePath : {
type : "string"
}
},
events : {},
aggregations : {
_conceptClause : {
type : "sparqlish.control.conceptClause",
multiple : false
},
_propertyClause : {
type : "sparqlish.control.propertyClause",
multiple : false
},
_conjunctionPropertyClause : {
type : "sparqlish.control.conjunctionPropertyClause",
multiple : false
}
}
},
init : function() {
var self = this;
self.setAggregation("_conceptClause", new sparqlish.control.conceptClause());
self.setAggregation("_propertyClause", new sparqlish.control.propertyClause());
self.setAggregation("_conjunctionPropertyClause", new sparqlish.control.conjunctionPropertyClause());
},
renderer : function(oRm, oControl) {
if (oControl.getClausePath() != undefined) {
// TODO no point if path not yet defined
oRm.write("<div ");
oRm.writeControlData(oControl);
oRm.writeClasses();
oRm.write(">");
var currentModel = oControl.getModel("queryModel");
// Set binding context, rather than just the binding path etc, as this seems essential for satisfactory binding of
// aggregations
oControl.setBindingContext(new sap.ui.model.Context(oQueryModel, oControl.getClausePath()), "queryModel")
var currentCtx = oControl.getBindingContext("queryModel");
var currentContext = oControl.getModel("queryModel").getProperty("", currentCtx);
if (currentContext != undefined) {
var sClass = currentContext._class;
if (sClass == "Query") {
oControl.setAggregation("_conceptClause", new sparqlish.control.conceptClause().setBindingContext(oControl.getBindingContext("queryModel")));
oRm.renderControl(oControl.getAggregation("_conceptClause"));
} else if (sClass == "Clause") {
oControl.setAggregation("_propertyClause", new sparqlish.control.propertyClause().setBindingContext(oControl.getBindingContext("queryModel")));
oRm.renderControl(oControl.getAggregation("_propertyClause"));
} else if (sClass == "ConjunctionClause") {
oControl.setAggregation("_conjunctionPropertyClause", new sparqlish.control.conjunctionPropertyClause().setBindingContext(oControl
.getBindingContext("queryModel")));
oRm.renderControl(oControl.getAggregation("_conjunctionPropertyClause"));
} else {
jQuery.sap.log.fatal("Incorrect class of provided query clause");
}
}
oRm.write("</div>");
} else {
jQuery.sap.log.fatal("clausePath not defined");
}
}
});
An example of one of the dependent controls is below.
jQuery.sap.require("sparqlish.control.conceptMenu");
jQuery.sap.require("sparqlish.control.conceptFilters");
jQuery.sap.require("sparqlish.control.addClause");
sap.ui.core.Control.extend("sparqlish.control.conceptClause", {
metadata : {
properties : {
concept : "object"
},
events : {},
aggregations : {
_concept : {
type : "sparqlish.control.conceptMenu",
multiple : false
},
_conceptFilters : {
type : "sparqlish.control.conceptFilters",
multiple : false
},
_addClause : {
type : "sparqlish.control.addClause",
multiple : false
}
}
},
init : function() {
var self = this;
var conceptSelect =function(oEvent){
var currentModel = self.getModel("queryModel");
var currentContext = self.getBindingContext("queryModel");
var currentModelData = currentModel.getProperty("", currentContext);
currentModelData.conceptFilters = [];
currentModelData.clauses = {};
var sConcept = oEvent.getParameter("concept");
var oMetaModel = self.getModel("metaModel");
var oConcept=oMetaModel.getODataEntitySet(sConcept);
self.setConcept( oConcept);
self.oEntityTypeModel = new sap.ui.model.json.JSONModel();
self.oEntityTypeModel.setData(oMetaModel.getODataEntityType(oConcept.entityType));
self.setModel(self.oEntityTypeModel, "entityTypeModel");
self.getAggregation("_conceptFilters").setModel(self.oEntityTypeModel, "entityTypeModel");
self.getAggregation("_conceptFilters").getAggregation("_extendFilter").setVisible(true);
currentModel.refresh();
self.rerender();
};
self.setAggregation("_concept", new sparqlish.control.conceptMenu({
selected : function(oEvent) {
self.getAggregation("_conceptFilters").getAggregation("_extendFilter").setVisible(true);
},
changed : conceptSelect
}).bindElement("queryModel>"));
self.setAggregation("_conceptFilters", new sparqlish.control.conceptFilters().bindElement("queryModel>"));
self.setAggregation("_addClause", new sparqlish.control.addClause({
pressed : function(oEvent) {
alert("concept");
}
}).bindElement("queryModel>"));
},
renderer : function(oRm, oControl) {
oRm.addClass("conceptClause");
oRm.write("<div ");
oRm.writeControlData(oControl);
oRm.writeClasses();
oRm.write(">");
oRm.write(sap.ui.getCore().getModel("i18nModel").getProperty("conceptClauseFind"));
oRm.renderControl(oControl.getAggregation("_concept"));
oRm.renderControl(oControl.getAggregation("_conceptFilters"));
oRm.write(" ");
oRm.renderControl(oControl.getAggregation("_addClause"));
oRm.write("</div>");
}
});

Paging with jsonRest in Ehancedgrid in dojo

i have 100000 records in database...i have to display 50 at a time in enhanced grid when i scroll down next request goes to server and get next 50 like wise ......
i came across that this can be achieved by jsonRestStore....i tried with that but i am not getting that..how to use jsonRest for this purpose ????..plz sugggest me answer
my code is
require([
"dojo/_base/lang", "dojox/grid/EnhancedGrid",
"dojox/grid/enhanced/plugins/Search","dojox/grid/enhanced/plugins/Filter",
"dojox/grid/enhanced/plugins/Pagination","dojo/data/ItemFileWriteStore",
"dojo/store/JsonRest","dijit/form/Button","dojo/request/xhr", "dojo/dom",
"dojo/dom-construct", "dojo/json", "dojo/on", "dojox/grid/cells/dijit",
"dojo/domReady!"
], function(lang,EnhancedGrid,Search,Filter,Pagination,ItemFileWriteStore,JsonRest,Button,xhr, dom, domConst, JSON, on) {
xhr("//myipaddress/GridExample/string", {
handleAs : "json"
}).then(function(dataa){
/* domConst.place("<p>response: <code>" + JSON.stringify(dataa) + "</code></p>", "output"); */
/* domConst.place("<p>response: <code>" + JSON.stringify(dataa) + "</code></p>", "output"); */
var mydata=dataa;
var yourStore = new dojo.data.ItemFileWriteStore({
data: {
identifier: "sno",
/* items: mydata.aa */
items:mydata
}
});
grid = new EnhancedGrid({
id:'grid',
store : yourStore,
structure : layout,
rowSelector: '20px',
plugins: {
search:true,
pagination: {
pageSizes: ["50","100","500","1000"],
description: true,
sizeSwitch: true,
pageStepper: true,
gotoButton: true,
maxPageStep: 2,
position: "bottom"
},
filter: {
closeFilterbarButton: true,
ruleCount: 5,
itemsName: "rows"
}
}
});
grid.placeAt("myGrid");
grid.startup();
}, function(err) {
alert("error");
}, function(evt) {
});
var id=100000;
var addbutton = new Button({
onClick: function (){
id++;
/* alert(dojox.grid.scroller.firstVisibleRow);
alert(dojox.grid.scroller.lastVisibleRow); */
console.log(arguments);
grid.store.newItem({
sno:id,
sname:'san',
salary:'25000'
});
store.save();
grid.render();
}
}, "addRow");
var removebutton = new Button({
onClick: function (){
var items = grid.selection.getSelected();
alert(items);
if(items.length){
dojo.forEach(items, function(selectedItem){
if(selectedItem !== null){
store.deleteItem(selectedItem);
store.save();
}
});
}
grid.render();
}
}, "removeRow");
var updatebutton = new Button({
onClick: function (){
}
}, "updateRow");
var store1 = new JsonRest({
target: "http://localhost:7080/GridExample/string"
});
store.get(3).then(function(item){
alert(item);
});
});
I am sure you must have found answer to your question by now. But to help others, You haven't tied your JsonRest store (store1) to grid.
Here is example code that does this:
//jsonstore
var jsonStore = new dojo.store.Cache(new dojo.store.JsonRest({
target : "http://localhost:7080/GridExample/string",
idProperty : "id"
}), dojo.store.Memory({
idProperty : "id"
}));
grid = new dojox.grid.EnhancedGrid({
store : dataStore = dojo.data.ObjectStore({
objectStore : jsonStore
}),
id: "grid_id",
structure : layout,
rowSelector : '20px',
selectionMode : "single",
clientSort : true,
plugins : {
selector : true,
/**nestedSorting : true,**/
pagination : {
defaultPageSize : 20,
pageSizes : [ 20, 50, 100, "All" ],
description : true, // display the current position
sizeSwitch : true, // display the page length menu
pageStepper : true, // display the page navigation choices
gotoButton : true, // go to page button
/*page step to be displayed*/
maxPageStep : 4,
/*position of the pagination bar*/
position : "bottom"
}
}
}, "search_results_grid"); // make sure you have a target HTML element with this id

How to show nested items in Sencha Touch list

I have following json data.
{
"pendingTasksVOs" : [{
"groupName" : "LAST_MONTH",
"documents" : [{
"description" : "kvk1",
"uploadDate" : "1-12-2012"
}
]
}, {
"groupName" : "OLDER",
"documents" : [{
"description" : "kvk2",
"uploadDate" : "1-11-2012"
}, {
"description" : "kvk3",
"uploadDate" : "1-10-2012"
}, {
"description" : "kvk4",
"uploadDate" : "1-01-2012"
}
]
}
]
}
I want to show it in Sencha Touch list grouped by GroupName .
I want list to be in following format:
GoupName : Group1
-----------------------------
Description11 , UploadDate11 This should be separate clickable list row
-----------------------------
Description12 , UploadDate12 This should be separate clickable list row
-----------------------------
Description13 , UploadDate13 This should be separate clickable list row
-----------------------------
******************************
GoupName : Group2
-----------------------------
Description21 , UploadDate21 This should be separate clickable list row
-----------------------------
Description22 , UploadDate22 This should be separate clickable list row
-----------------------------
******************************
I am trying to use Sencha Touch List component. But I am not to get the list as per above requirements
//This is my store
var store = Ext.create('Ext.data.Store', {
model: 'Demo.model.DocumentList',
rootProperty: 'pendingTasksVOs',
autoLoad: true,
grouper: {
groupFn: function(record) {
if (record && record.data.title) {
return record.get('groupName');
} else {
return '';
}
}
}
});
//template for list item
var listTemplate = new Ext.XTemplate(
'<tpl for=".">',
'{groupName}</br>',
'<ul>',
'<tpl for="documents">',
'{description} {uploadDate} </br>',
'</tpl>',
'</ul>',
'</tpl>'
);
// Initialize the main view
Ext.getCmp("pendingTasksListId").add(Ext.create('Ext.List', {
fullscreen: true,
itemTpl: listTemplate,
store: store,
groupField:'description',
grouped: true
}));
//DocumentListModel is defined under /app/model/
Ext.define('Demo.model.DocumentList', {
extend: 'Ext.data.Model',
requires : ['Demo.model.Doc'],
config: {
fields: ['groupName', 'documents'],
hasMany : {
model : "Demo.model.Doc",
associationKey: 'documents'
},
proxy: {
type: 'rest',
url : "/getPendingTasks",
reader: {
type: 'json',
rootProperty : 'pendingTasksVOs'
}
}
}
}
//Document Model is defined under /app/model/
Ext.define('Demo.model.Doc', {
extend: 'Ext.data.Model',
config: {
fields: ['description', 'uploadDate'],
belongsTo: "Demo.model.DocumentList"
}
});
});
I am able to get the list item as follows:
GroupName,
Description11,UploadDate11
Description12,UploadDate12
But above whole content is clickable. I want to have each Description & UploadDate pair to be clickable.
Can anyone guide me on how can I achieve above stated requirement?
I got the solution for my question.
Create following custom json reader under /app/reader/ folder as CustomReader.js
Ext.define('Demo.reader.CustomReader', {
extend: 'Ext.data.reader.Json',
alias: 'reader.customReader',
getData: function(data) { // overriding
data = this.callParent(arguments);
var responseString = Ext.encode(data);
var json = JSON.parse(responseString);
var result = [];
Ext.each(json.pendingTasksVOs, function(entry) {
var groupName = entry.groupName;
Ext.each(entry.documents || [], function(document) {
result.push({
description : document.description,
uploadDate: document.uploadDate,
groupName: groupName
});
});
});
return result;
}
});
Doc model should be created at /app/model as follows as Doc.js
Ext.define('Demo.model.Doc', {
extend: 'Ext.data.Model',
config: {
fields: ['description','uploadDate','groupName']
}
});
Store can be created at /app/store folder
Store should use this custom reader as follows:
Ext.define("Demo.store.DocumentStore", {
extend:'Ext.data.Store',
requires:['Demo.model.Doc' , 'Ext.data.proxy.Rest', 'Demo.reader.CustomReader'],
id:'DocumentStore1',
config:{
model:'Demo.model.Doc',
autoLoad:true,
grouper:{
groupFn:function (record) {
if (record && record.data.groupName) {
return record.get('groupName');
} else {
return '';
}
}
},
proxy:{
type:'rest',
url:"/getPendingTasks",
reader:{
type:'customReader' //This is our custom reader
}
}
}
});
//Finally You can create the list as follows
Ext.create('Demo.store.DocumentStore');
// Initialize the main view
Ext.getCmp("pendingTasksListId").add(Ext.create('Ext.List', {
fullscreen:true,
itemTpl:'<div class="contact">{description} {uploadDate} {groupName} </div>',
store: 'DocumentStore1',
grouped:true
}));
Above gives me the list where I get separate row for each {description} {uploadDate} pair from the received json specified in question
Try this,
itemTpl: [
'<div>GroupName : {groupName}</div>',
'<div>',
'<ul>',
'<tpl for="documents">',
'<li>{description} , {uploadDate}</li>',
'</tpl>',
'</ul>',
'</div>',
].join('')
OR this,
itemTpl: [
'<div>GroupName : {groupName}</div>',
'<div>',
'<ul>',
'<tpl for="documents">',
'<li><div onclick="whateverYouWantToDo()">{description} , {uploadDate}</div></li>',
'</tpl>',
'</ul>',
'</div>',
].join('')