I have an Angular app that retrieves my data from the server and would like to use the results to populate a kendo grid. I have tried to create a kendo.data.DataSource but can not get the grid to populate. Below is what I am trying.
$scope.surchargeGridOptions = {
dataSource: {
pageSize: 15,
autoSync: true,
autoBind: false,
data: $scope.model.dataSource,
}
$scope.getWaivers = function () {
waiverService.getCustomers($scope.model.customer.CustomerID).then(function (result) {
$scope.model.waivers = result.data;
$scope.model.dataSource = new kendo.data.DataSource({
data: $scope.model.waivers,
});
$scope.model.dataSource.read();
});
};
Is it possible to do this and how should I go about it?
The data source object in your options has a data property that only requires a reference to a plain array, not an entire kendo data source.
You should use k-data-source to reference your data...
<kendo-grid k-data-source="myData"></kendo-grid>
... and you don't strictly need a kendo data source to get it working...
$scope.myData = [
{ name: 'a', number: 1 },
{ name: 'b', number: 1 },
{ name: 'c', number: 1 },
{ name: 'd', number: 1 }
];
.. If you have dynamic data then a kendo observable array would be best practice.
Here is a code pen example.
Front Html Page having Grid option
<div kendo-grid="ListGrid" options="ListOptions" k-rebind="ListOptions" class="k-grid-content-border"></div>
function GridColumn() {
return [{
field: 'name',
template: "<a ng-click='ToList(this.dataItem)' class='cursor-pointer'>{{this.dataItem.name}}</a>",
title: "",
footerTemplate: "Total",
width: 200,
locked: true,
}]}
$scope.ToGeo = function (item) {
$scope.dataLoded = false;
GetResults(function (res) {
$scope.ListOptions.dataSource = new kendo.data.DataSource({
data: res,
});
$scope.ListOptions.columns = GridColumn();
$scope.ListGrid.refresh();
$scope.dataLoded = true;
})
}
where GetResults is for API call and fetching data
Related
I am using Master detail in Kendo Grid in AngularJS.
Here is the setup of the code:
In cshtml is:
<script type="text/x-kendo-template" id="template">
<div>
<div class="orders"></div>
</div>
</script>
In the AngularJS controller is
The MasterRowId is the id of the Column in the Master row. So the Master grid is a grid with
columns Id and name
$scope.getorders = function (masterRowId)
{
myservice.getorders(masterRowId)
.then(function (result) {
for (var j = 0; j < result.data.length; j++)
$scope.ordergroupdata.push(result.data[j]);
});
}
In the master grid definition i have
......
detailTemplate: kendo.template($("#template").html()),
detailInit: $scope.detailInit,
The definition of $scope.detailInit is
$scope.detailInit = function (e)
{
$scope.MasterRowId = e.data.Id;
$scope.getorders ($scope.MasterRowId);
var orderdata = $scope.ordergroupdata;
var orderdatasource = new kendo.data.DataSource({
transport: {
read: function (e) {
e.success(orderdata);
},
update: function (e) {
e.success();
},
create: function (e) {
var item = e.orderdata;
item.Id = orderdata.length + 1;
e.success(item);
}
},
schema: {
model: {
id: "Id",
fields: {
OrderId: { type: 'string'},
}
}
},
});
e.detailRow.find(".orders").kendoGrid({
dataSource: orderdatasource,
columns: [
{ field: "OrderId", title: "OrderId" },
]
});
}
The issue is that if i click on the first row , i can retrieve the data according to the MasterRowId from my MVC action method. So If i click on the first row and the MasterRowId is for example 10 , then i get an OrderId of "1234" .
I can click on the second row with MasterRowID of 15 and it will retrieve the OrderId of "8231", BUT if i go back to the first row the data (OrderId) in the details grid is actually the data from the second row, so its "8321" NOT "1234".
How can i always call the $scope.detailInit so that i can go back to the MVC Action method and always retrieve the correct data for that particular row with that MasterRowId ?
Once i expand the row and move on to another row , the detailsInit doesnt get called any more for that row ?
detailInit is only called on first expand, but you can use detailExpand that is called every time you expand the detail table.
Offical example:
<script>
$("#grid").kendoGrid({
columns: [
{ field: "name" },
{ field: "age" }
],
dataSource: [
{ name: "Jane Doe", age: 30 },
{ name: "John Doe", age: 33 }
],
detailTemplate: "<div>Name: #: name #</div><div>Age: #: age #</div>",
detailExpand: function(e) {
console.log(e.masterRow, e.detailRow);
}
});
</script>
Docs: detailExpand
Official example: detailExpand example
I have a paging grid with local store, and I want to apply a filter using my own function. But it is failed.
From internet recommendations I used remoteFilter: true and enablePaging: true options in store config.
And it works perfectly if I filter store with specific configuration object:
store.filter([{ property: 'age', value: 12 }]);
unfortunately it is not enough to build complex filter criteria.
In accordance with documentation there is a special filterBy method in store object to use function as filter. But, when I am providing it like this:
store.filterBy( function( record ) {
return record.get( 'age' ) <= 12;
});
I got an error Uncaught Error: Unable to use a filtering function in conjunction with remote filtering.
Here is my working example in fiddle https://fiddle.sencha.com/#fiddle/2u8l
This is my store configuration and all business logic from controller. I'll skip view configuration here to focus on main part( IMO )of code
Ext.define('TestGridViewModelr', {
extend: 'Ext.app.ViewModel',
alias: 'viewmodel.myexmpl.main.testgrid',
data: {
},
formulas: {},
stores: {
simpsons: {
model: 'Ext.data.Model',// 'SimpsonModel',
pageSize: 2,
// remoteSort: true,
remoteFilter: true,
proxy: {
type: 'memory',
enablePaging: true,
reader: {
type: 'json',
rootProperty: 'items'
}
}
}
}
});
Ext.define('TestGridController', {
extend: 'Ext.app.ViewController',
alias: 'controller.myexmpl.main.testgrid',
init: function () {
console.log('controller inititalized\n init async store loading...');
setTimeout( this.onStoreLoad.bind( this ), 1000 );
},
initViewModel: function(vm){
console.log( 'viewModel init', vm.get('test') );
},
emptyMethod: function () {},
onStoreLoad: function () {
console.log('loading store');
var vm = this.getViewModel();
var store = vm.getStore('simpsons');
store.getProxy().data = this.getSimpsonsData().items;
store.reload();
// store.loadData( this.getSimpsonsData() );
},
//++++++++++++ FILTERING ++++++++
/* NO PROBLEM */
onToggleFilter: function () {
console.log('simple filter');
var filter = this.getSimpleFilter()
this.toggleFilter( filter );
},
/* PROBLEM */
onToggleFnFilter: function(){
console.log('function filter');
// var filterFn = this.filterChildren;
var filterFn = this.getFilterUtil()
this.toggleFilter( filterFn );
},
/* NO PROBLEM */
getSimpleFilter: function(){
return {
property: 'age',
value: '12'
};
},
/* PROBLEM */
getFilterUtil: function() {
return Ext.create( 'Ext.util.Filter', {
filterFn: this.filterChildren
})
},
filterChildren: function( record ) {
var age = record.get( 'age' );
console.log( 'filter record up to age:', age )// debugger;
return parseInt( age ) <= 12;
},
toggleFilter: function( fltr ) {
var store = this.getViewModel().getStore( 'simpsons' );
var filters = store.getFilters();
if ( filters.length > 0 ) {
store.clearFilter();
} else {
this. applyFilterToStore( fltr, store );
}
},
applyFilterToStore: function( filter, store ){
var method = Ext.isFunction( filter ) || filter instanceof Ext.util.Filter
? 'filterBy'
: 'setFilters';
store[method]( filter );
},
getSimpsonsData: function(){
return {
'items': [{
'name': 'Lisa',
'age': 12,
"email": "lisa#simpsons.com",
"phone": "555-111-1224"
}, {
'name': 'Bart',
'age': 8,
"email": "bart#simpsons.com",
"phone": "555-222-1234"
}, {
'name': 'Homer',
'age': 40,
"email": "homer#simpsons.com",
"phone": "555-222-1244"
}, {
'name': 'Marge',
'age': 34,
"email": "marge#simpsons.com",
"phone": "555-222-1254"
}]
}
}
});
In general I want to have ability to set up filter criteria on paging grid with local store programmatically. Function allows me to extend filter capabilities and build flexible logical expression using conjunction and disquisition. For example:
name.lenght <= 4 && ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)
Thank you in advance,
A.
You can't use both remoteFilter and filterBy in one store. Decide where should be the logic of the filter - on Client Side or Server Side?
If on server side, set the remoteFilter as true and use filter action with extra paramaters which you can catch on server and perform the filter.
If on client side, set the remoteFilter as false and use filterBy function like you attached.
Check the example on fiddle (I just changed a few things): https://fiddle.sencha.com/#fiddle/2ua4&view/editor
I have finally resolved this issue!
Mentioned error raised in onFilterEndUpdate method of store in next lines:
...
me.getFilters().each(function(filter) {
if (filter.getInitialConfig().filterFn) {
Ext.raise('Unable to use a filtering function in conjunction with remote filtering.');
}
});
...
I have override this method in my store entity and commented out these lines.
I know it is not best solution, but I could not find better one.
Here is the complete solution concerning this topic:
Configure store with remoteFilter: true and enablePaging: true options:
{
model: 'Ext.data.Model',
pageSize: 2,
remoteFilter: true,
proxy: {
type: 'memory',
enablePaging: true,
reader: {
type: 'json'
}
}
}
Load data into the store using its Proxy instead of loadData method:
store.getProxy().data = this.getSimpsonsData().items;
store.reload();
Override method onFilterEndUpdate after store initialization and comment out mentioned lines i.e:
onStoreLoad: function() {
...
store.onFilterEndUpdate = this.onFilterEndUpdate.bind( store );
...
},
onFilterEndUpdate: function() {
var me = this
, suppressNext = me.suppressNextFilter
, filters = me.getFilters(false);
// If the collection is not instantiated yet, it's because we are constructing.
if (!filters) {
return;
}
if (me.getRemoteFilter()) {
// me.getFilters().each(function(filter) {
// if (filter.getInitialConfig().filterFn) {
// Ext.raise('Unable to use a filtering function in conjunction with remote filtering.');
// }
// });
me.currentPage = 1;
if (!suppressNext) {
me.load();
}
} else if (!suppressNext) {
me.fireEvent('datachanged', me);
me.fireEvent('refresh', me);
}
if (me.trackStateChanges) {
// We just mutated the filter collection so let's save stateful filters from this point forward.
me.saveStatefulFilters = true;
}
// This is not affected by suppressEvent.
me.fireEvent('filterchange', me, me.getFilters().getRange());
}
Here is live example in fiddle https://fiddle.sencha.com/#fiddle/2ub7
I have a checkbox group which will have a dynamic number of checkboxes. The backend returns data containing the label and the input value. I loop these records and generate a checkbox object for each one. But when I pass the generated array into the items array, nothing happens.
Here are snippets of my checkbox group class.
Ext.define("MyApp.view.form.field.CheckboxGroup",{
extend:"Ext.form.CheckBoxGroup",
...
...
initComponent:function(){
this.items = getCheckboxes();
...
this.callParent(arguments);
},
getCheckboxes:function(){
Ext.Ajax.request({
url:"blah/getcheckboxes",
scope:this,
success:function(resp_){
var resp = Ext.JSON.decode(resp_.responseText);
var checkboxesArr = [];
if(resp.data){
for(var i=0; i<resp.data.length; i++){
checkboxesArr.push({boxLabel:resp.data[i].label, inputValue:resp.data[i].id, ....});
}
}
return checkboxesArr;
});
/*return checkboxesArr = [
{boxLabel: 'Yes', name: this.name, inputValue: 'Y'},
{boxLabel: 'No', name: this.name, inputValue: 'N'}
];*/
}
If I uncomment the static checkboxesArr with the 2 checkboxes and return that instead it works, but it doesnt work with the checkboxesArr generated with the backend response.
Thanks
The ajax call is asynchronous so you can add the items instead:
getCheckboxes: function () {
Ext.Ajax.request({
url: "data1.json",
scope: this,
success: function (resp_) {
var resp = Ext.JSON.decode(resp_.responseText);
var checkboxesArr = [];
if (resp.data) {
for (var i = 0; i < resp.data.length; i++) {
checkboxesArr.push({
boxLabel: resp.data[i].label,
inputValue: resp.data[i].id
});
}
}
this.add(checkboxesArr);
}
});
}
Working example: https://fiddle.sencha.com/#view/editor&fiddle/1lgc
I am using ui grid to show a list of data and I am trying to initially expand all rows.
I am trying to do this in the onRegisterApi event:
scope.GridOptions =
{
data: properties,
columnDefs:
[
{ name: "Full Address", field: "FullAddress" },
{ name: "Suburb", field: "Suburb" },
{ name: "Property Type", field: "PropertyType" },
{ name: "Price", field: "Price", cellFilter: 'currency'},
{ name: "Status", field: "Status" },
{ name: "Sale Type", field: "SaleType" },
{ name: "Date Created", field: "CreateDate", cellFilter: "date:'dd/MM/yyyy HH:mma'"}
],
expandableRowTemplate: 'template.html',
expandableRowHeight: 200,
onRegisterApi: (gridApi) =>
{
scope.gridApi = gridApi;
gridApi.expandable.on.rowExpandedStateChanged(scope,(row) =>
{
if (row.isExpanded) {
this.scope.GridOptions.expandableRowScope = row.entity;
}
});
gridApi.expandable.expandAllRows();
}
};
But the code above does not work. It looks like when I call expandAllRows() the rows are not rendered yet.
In my case, the following worked:
$scope.gridOptions = {
...
onRegisterApi: function(gridApi) {
$scope.gridApi = gridApi;
$scope.gridApi.grid.registerDataChangeCallback(function() {
$scope.gridApi.treeBase.expandAllRows();
});
}
};
I find I can expand all rows by using rowsRendered event:
gridApi.core.on.rowsRendered(scope,() => {
if (!gridApi.grid.expandable.expandedAll && !initialized)
{
gridApi.expandable.expandAllRows();
initialized = true;
}
});
I have used a variable initialized to identify if this is the first time rows are rendered as I only want to expand all rows initially.
None of the above worked for me for all of my grid use cases.
$scope.gridApi.grid.registerDataChangeCallback(function() {
if($scope.gridApi.grid.treeBase.tree instanceof Array){
$scope.gridApi.treeBase.expandAllRows();
}
});
The following works in every case I have tested. DataChangeCallback is called twice (for some unknown reason) on initial page load. The first time, gridApi.grid.treeBase.tree is an object which causes the issue with gridApi.grid.treeBase.tree.forEach above:
None of these answers worked for me, the following did:
scope.gridApi.core.on.rowsRendered(null, () => {
scope.gridApi.treeBase.expandAllRows();
});
The following worked for me, but no guarantee that it won't break anything... (looks good in my tests):
You need to change the source code, for example in ui-grid.js, i.e. the one your are deploying with your app:
In the addOrUseNode: function(...) inside the createTree: function(...) simply change COLLAPSED to EXPANDED for newNodes:
addOrUseNode: function (grid, row, parents, aggregationBase) {
...
var newNode = { state: uiGridTreeBaseConstants.EXPANDED, row: row, parentRow: null, aggregations: newAggregations, children: [] };
...
}
In module.service('uiGridTreeBaseService'... initializeGrid: function(grid) set grid.treeBase.expandAll from false to true (to let the tree know that all rows are expanded on initialitation)
[looks this is optional for the treeView]: Do the same In module.service('uiGridExpandableService', ['gridUtil', function (gridUtil) {...} in initializeGrid: function (grid). Change grid.expandable.expandedAll from false to true
The goal is to use buffered store for the dynamic data set.
The workflow is below:
Some data is already present on server.
Clients uses buffered store & infinite grid to handle the data.
When the application runs the store is loading
and 'load' event scrolls the grid to the last message.
Some records are added to server.
Client gets a push notification and runs store reload.
topic.store.load({addRecords: true});
The load event runs and tries to scroll to the last message again but failes:
TypeError: offsetsTo is null
e = Ext.fly(offsetsTo.el || offsetsTo, '_internal').getXY();
Seems that the grid view doesn't refreshes and doesn't show the added records, only the white spaces on their places.
Any ideas how can I make the grid view refresh correctly?
The store initialization:
Ext.define('orm.data.Store', {
extend: 'Ext.data.Store',
requires: ['orm.data.writer.Writer'],
constructor: function (config) {
Ext.apply(this, config);
this.proxy = Ext.merge(this.proxy, {
type: 'rest',
batchActions: true,
reader: {
type: 'json',
root: 'rows'
},
writer: {
type: 'orm'
}
});
this.callParent(arguments);
}
});
Ext.define('akma.chat.model.ChatMessage', {
extend:'Ext.data.Model',
fields:[
{ name:'id', type:'int', defaultValue : undefined },
{ name:'createDate', type:'date', dateFormat:'Y-m-d\\TH:i:s', defaultValue : undefined },
{ name:'creator', type:'User', isManyToOne : true, defaultValue : undefined },
{ name:'message', type:'string', defaultValue : undefined },
{ name:'nameFrom', type:'string', defaultValue : undefined },
{ name:'topic', type:'Topic', isManyToOne : true, defaultValue : undefined }
],
idProperty: 'id'
});
Ext.define('akma.chat.store.ChatMessages', {
extend: 'orm.data.Store',
requires: ['orm.data.Store'],
alias: 'store.akma.chat.store.ChatMessages',
storeId: 'ChatMessages',
model: 'akma.chat.model.ChatMessage',
proxy: {
url: 'http://localhost:8080/chat/services/entities/chatmessage'
}
});
var store = Ext.create('akma.chat.store.ChatMessages', {
buffered: true,
pageSize: 10,
trailingBufferZone: 5,
leadingBufferZone: 5,
purgePageCount: 0,
scrollToLoadBuffer: 10,
autoLoad: false,
sorters: [
{
property: 'id',
direction: 'ASC'
}
]
});
Grid initialization:
Ext.define('akma.chat.view.TopicGrid', {
alias: 'widget.akma.chat.view.TopicGrid',
extend: 'akma.chat.view.grid.DefaultChatMessageGrid',
requires: ['akma.chat.Chat', 'akma.UIUtils', 'Ext.grid.plugin.BufferedRenderer'],
features: [],
hasPagingBar: false,
height: 500,
loadedMsg: 0,
currentPage: 0,
oldId: undefined,
forceFit: true,
itemId: 'topicGrid',
selModel: {
pruneRemoved: false
},
multiSelect: true,
viewConfig: {
trackOver: false
},
plugins: [{
ptype: 'bufferedrenderer',
pluginId: 'bufferedrenderer',
variableRowHeight: true,
trailingBufferZone: 5,
leadingBufferZone: 5,
scrollToLoadBuffer: 10
}],
tbar: [{
text: 'unmask',
handler: function(){
this.up('#topicGrid').getView().loadMask.hide();
}
}],
constructor: function (config) {
this.topicId = config.topicId;
this.store = akma.chat.Chat.getMessageStoreInstance(this.topicId);
this.topic = akma.chat.Chat.getTopic(this.topicId);
var topicPanel = this;
this.store.on('load', function (store, records) {
var loadedMsg = store.getTotalCount();
var pageSize = store.pageSize;
store.currentPage = Math.ceil(loadedMsg/pageSize);
if (records && records.length > 0) {
var newId = records[0].data.id;
if (topicPanel.oldId) {
var element;
for (var i = topicPanel.oldId; i < newId; i++) {
element = Ext.get(i + '');
topicPanel.blinkMessage(element);
}
}
topicPanel.oldId = records[records.length-1].data.id;
var view = topicPanel.getView();
view.refresh();
topicPanel.getPlugin('bufferedrenderer').scrollTo(store.getTotalCount()-1);
}
});
this.callParent(arguments);
this.on('afterrender', function (grid) {
grid.getStore().load();
});
var me = this;
akma.UIUtils.onPasteArray.push(function (e, it) {
if(e.clipboardData){
var items = e.clipboardData.items;
for (var i = 0; i < items.length; ++i) {
if (items[i].kind == 'file' && items[i].type.indexOf('image/') !== -1) {
var blob = items[i].getAsFile();
akma.chat.Chat.upload(blob, function (event) {
var response = Ext.JSON.decode(event.target.responseText);
var fileId = response.rows[0].id;
me.sendMessage('<img src="/chat/services/file?id=' + fileId + '" />');
})
}
}
}
});
akma.UIUtils.addOnPasteListener();
},
sendMessage: function(message){
if(message){
var topicGrid = this;
Ext.Ajax.request({
method: 'POST',
url: topicGrid.store.proxy.url,
params:{
rows: Ext.encode([{"message":message,"topic":{"id":topicGrid.topicId}}])
}
});
}
},
blinkMessage: function (messageElement) {
if (messageElement) {
var blinking = setInterval(function () {
messageElement.removeCls('red');
messageElement.addCls('yellow');
setTimeout(function () {
messageElement.addCls('red');
messageElement.removeCls('yellow');
}, 250)
}, 500);
setTimeout(function () {
clearInterval(blinking);
messageElement.addCls('red');
messageElement.removeCls('yellow');
}, this.showInterval ? this.showInterval : 3000)
}
},
columns: [ {
dataIndex: 'message',
text: 'Message',
renderer: function (value, p, record) {
var firstSpan = "<span id='" + record.data.id + "'>";
var creator = record.data.creator;
return Ext.String.format('<div style="white-space:normal !important;">{3}{1} : {0}{4}</div>',
value,
creator ? '<span style="color: #' + creator.chatColor + ';">' + creator.username + '</span>' : 'N/A',
record.data.id,
firstSpan,
'</span>'
);
}
}
]
});
upd: Seems that the problem is not in View. The bufferedrenderer plugin ties to scroll to the record.
It runs a callback function:
callback: function(range, start, end) {
me.renderRange(start, end, true);
targetRec = store.data.getRange(recordIdx, recordIdx)[0];
.....
store.data.getRange(recordIdx, recordIdx)[0]
tries to get the last record in the store.
....
Ext.Array.push(result, Ext.Array.slice(me.getPage(pageNumber), sliceBegin, sliceEnd));
getPage returns all records of the given page, but the last record is missing i.e. the store was not updated perfectly.
Any ideas how to fix?
The problem is that store.load() doesn't fill up store PageMap with the new data. The simplest fix is using store.reload() instead.
Maybe you are to early when listening to the load event. I am doing roughly the same in my application (not scrolling to the end, but to some arbitrary record after load). I do the view-refresh and bufferedrender-scrollTo in the callback of the store.load().
Given your code this would look like:
this.on('afterrender', function (grid) {
var store = grid.getStore();
store.load({
callback: function {
// snip
var view = topicPanel.getView();
view.refresh();
topicPanel.getPlugin('bufferedrenderer').scrollTo(store.getTotalCount()-1);
}
});
});