Angular with Kendo, Using Grid Values Asynchronously - javascript

Ok I'm pretty sure I know exactly what I need to do here but I'm not sure how to do it. Basically I have a grid that I want to make a key column bind to an array of key/values, which I've done before with kendo (not using Angular) and I know that when I'm creating my key/value array asynchronously then that needs to complete before I can get them show-up with kendo, which I have done using promises before.
So here I have the same issue only angular is also involved. I need to fetch and format an array of data into the format in which a kendo grid column can digest it, so no problem here is my controller code:
var realm = kendo.data.Model.define({
id: 'realmID',
fields: {
realmID: { editable: false, nullable: true }
realmType: { type: 'string', validation: { required: true } }
}
})
var ds1 = kendoHelpers.dataSourceFactory('realms', realm, 'realmID')
var realmType = kendo.data.Model.define({
id: 'realmTypeID',
fields: {
realmTypeID: { editable: false, nullable: true },
name: { type: 'string', validation: { required: true } }
}
})
var ds2 = kendoHelpers.dataSourceFactory('realms/types', realmType, 'realmTypeID')
$scope.mainGridOptions = {
dataSource: ds1,
editable: true,
navigatable: true,
autoBind:false,
toolbar: [
{ name: "create" },
{ name: 'save' },
{ name: 'cancel' }
],
columns: [
{ field: 'realmID', title: 'ID' }
{ field: 'realmTypeID', title: 'Realm Type', editor: realmTypesDDL, values: $scope.realmTypeValues },
{ command: "destroy" }
]
}
$scope.secondGridOptions = {
dataSource: ds2,
editable: true,
navigatable: true,
toolbar: [
{ name: "create" },
{ name: 'save' },
{ name: 'cancel' }
],
columns: [
{ field: 'realmTypeID', title: 'ID' },
{ field: 'name', title: 'Name' }
{ command: "destroy" }
]
}
ds2.fetch(function () {
$scope.realmTypeValues = [{ text: 'Test', value: "24bc2e62-f761-4e70-804c-bc36fdeced3d" }];
//this.data().map(function (v, i) {
// $scope.realmTypeValues.push({ text: v.name, value: v.realmTypeID})
//});
//$scope.mainGridOptions.ds1.read()
});
function realmTypesDDL(container, options) {
$('<input />')
.appendTo(container)
.kendoDropDownList({
dataSource: ds2,
dataTextField: 'name',
dataValueField: 'realmTypeID'
});
}
I made this dataSourceFatory helper method above to return me a basic CRUD kendo dataSource that uses transport and also injects an authorization header which is working fine so don't get hung up on that, ultimately I'm going to be using this data in another grid as well as for reference values for the main grid, but I've hard coded some values that I can use to test with in the ds2.fetch callback.
My HTML is pretty plain:
<div>
<h2>Realms</h2>
<kendo-grid options="mainGridOptions"></kendo-grid>
<h2>Realm Types</h2>
<kendo-grid options="secondGridOptions"></kendo-grid>
</div>
This all works fine and well except I am only seeing the GUID of the realmTypeID in the grid, I click it and the editor is populated correctly so that's good but I want the text value to be displayed instead of the GUID. I'm sure the issue is that the array of values is empty whenever angular is binding to the grid options. My questions are:
How do I either delay this bind operation or manually rebind it after the fetch call?
Is there a better way to handle a situation like this? I try not to expend finite resources for no reason (IE making server calls when unnecessary)
Note: When I move the creation of the text/value array to happen before the grid options, I get the desired behavior I am after
EDIT A work around is to not use the directive to create the grid and instead defer the grid creation until the callback of whatever data your column is dependent on, I was hoping for a more elegant solution but this is better than nothing. So your HTML becomes something like
<h2>Realms</h2>
<div id="realms"></div>
<h2>Realm Types</h2>
<kendo-grid options="secondGridOptions"></kendo-grid>
Then you can create the grid in the fetch callback for example:
ds2.fetch(function () {this.data().map(function (v, i) {
$scope.realmTypeValues.push({ text: v.name, value: v.realmTypeID})
});
$('#realms').kendoGrid($scope.mainGridOptions);
$scope.mainGridOptions.dataSource.fetch()
});
But this doesn't feel very angularish so I'm really hoping for a better solution!

Ok...well I think I hacked this enough and without another suggestion I'm going to go forward with this approach. I'm just going to move the binding logic to the requestEnd event of the second grid so that the values array can be populated right before the binding even. I'm also reworking the values array in this method. It is a bit weird though, I think there is some kendo black magic going on with this array because I can't just set it to a new empty array without it breaking completely...which is why I'm poping everything out prior to repopulating the array. That way when something is deleted or edited in the second grid, the DDL in the first grid is updated in the callback.
function requestEnd(e) {
for (var i = $scope.realmTypeValues.length; i >= 0; i--) $scope.realmTypeValues.pop();
var data;
if (e.type == "read")
data = e.response;
else
data = e.sender.data();
data.map(function (v, i) { $scope.realmTypeValues.push({ text: v.name, value: v.realmTypeID }); });
if ($('#realms').data('kendoGrid') == undefined) {
$('#realms').kendoGrid($scope.mainGridOptions);
}
else
$('#realms').data('kendoGrid').columns[4].values = $scope.realmTypeValues;
}
ds2.bind('requestEnd', requestEnd);
So I'm going to accept my own answer unless anyone has a better approach!

Related

Automatically create header from JSON file, Bootstrap-table

I'm working with this bootstrap library and actually everything works fine. The question is, Can bootstrap-table generate header automatically in depend of JSON file? I've tried to find any information about that, but unlucky. Now my header is generated from script like from this example:
function initTable() {
$table.bootstrapTable({
height: getHeight(),
columns: [{
field: 'field1',
title: 'title1',
sortable: true
}, {
field: 'field2',
title: 'title2',
sortable: true
}, {
field: 'field3',
title: 'title3',
sortable: true
}, {
field: 'Actions',
title: 'Item Operate',
align: 'center',
events: operateEvents,
formatter: operateFormatter
}
],
formatNoMatches: function () {
return "This table is empty...";
}
});
Does anyone how to generate header automatically?
Populating from a flat json file is definetly possible but harder than from a seperate (slimmer and preped) data request, because title and other attributes 'might' have to be guessed at.
Ill show basic approach, then tell you how to make it work if stuck with a flat file that you CAN or CANT affect the format of (important point, see notes at end).
Make a seperate ajax requests that populates var colArray = [], or passes direct inside done callback.
For example, in callback (.done(),.success(), ect) also calls to the function that contains the js init code for the table.
You might make it look something like this:
function initTable(cols) {
cols.push({
field: 'Actions',
title: 'Item Operate',
align: 'center',
events: operateEvents,
formatter: operateFormatter
});
$("#table").bootstrapTable({
height: getHeight(),
columns: cols,
formatNoMatches: function () {
return "This table is empty...";
}
});
}
$(document).ready(function(){
$.ajax({
method: "POST",
url: "data/getColumns",
// data: { context: "getColumns" }
datatype: "json"
})
.done(function( data ) {
console.log( "getCols data: ", data );
// Prep column data, depending on what detail you sent back
$.each(data,function(ind,val){
data.sortable = true;
});
initTable(data);
});
});
Now, if you are in fact stuck with a flat file, point the ajax towards that then realise the question is whether you can edit the contents.
If yes, then add a columns array into it with whatever base data (title, fieldname, ect) that you need to help build your columns array. Then use responseHandler if needed to strip that columns array if it causes issues when loading into table.
http://bootstrap-table.wenzhixin.net.cn/documentation/#table-options
http://issues.wenzhixin.net.cn/bootstrap-table/ (click 'see source').
If no, you cant edit contents, and only have the fieldname, then look at using that in the .done() handler with whatever string operation (str_replace(), ect) that you need to make it look the way you want.

Display Custom Boolean Value in Angular ui-grid

Ok, I'm new to angular and angular ui-grid.
I'm using angularjs(v1.4) with angular-ui-grid(v3.0.7).
I have defined a grid as below
seec.gridOptions = {};
seec.gridOptions.rowEditWaitInterval = -1;
seec.gridOptions.onRegisterApi = function (gridApi) {
$scope.gridApi = gridApi;
gridApi.rowEdit.on.saveRow($scope, $scope.saveRow);
};
seec.gridOptions.columnDefs = [
{name: 'pouch', displayName: 'Pouch', enableCellEdit: false, enableHiding: false, width: 250},
{name: 'content', displayName: 'Content', enableHiding: false, width: 150},
{
name: 'units',
displayName: 'Number of Items',
type: 'number',
enableHiding: false,
width: 150
},
{name: 'active', displayName: 'Status', type: 'boolean', enableHiding: false, width: 150}
];
The controller basically makes a http call and feeds data to the grid.
if (response.status === 200) {
seec.gridOptions.data = angular.copy(seec.data);
}
Currently, the last item in the grid is being displayed as either 'true' or 'false' based on the boolean field value., and when I double click on the field a checkbox appears.
So, I need to display true as 'active' and false as 'inactive'.
Is there any way of doing this with angular ui-grid?
There certainly is! One approach could be to use a cellTemplate and map your rowvalues to something different.
I created a Plunkr showcasing a possible setup.
There are two steps to take. First add a cellTemplate to your column:
cellTemplate: "<div ng-bind='grid.appScope.mapValue(row)'></div>"
Note: Instead of ng-bind you could also use "<div>{{grid.appScope.mapValue(row)}}</div>", if you are more familiar with that.
Second step is to define your mapping function, for example:
appScopeProvider: {
mapValue: function(row) {
// console.log(row);
return row.entity.active ? 'active' : 'inactive';
},
}
#CMR thanks for including the Plunkr. As I was looking at it I checked, and in this case it seems overkill to have the mapValue function.
This worked for me:
cellTemplate: "<div class='ui-grid-cell-contents'>{{row.entity.active ? 'active' : 'inactive'}}</div>"
(I added the class in there to match the other cells). I will say that this still smells a little hacky to me.
This question leads to using a function as the field itself: In ui-grid, I want to use a function for the colDef's field property. How can I pass in another function as a parameter to it?
I'd still like to see an answer with the logic directly in the columnDefs.
You can use angular filter specifying in your columnDef for a column cellFilters : 'yourfiltername:args'.
args can be a variable or a value, in that case pay attention to use right quoting. if args is a string cellFilters : 'yourfiltername:"active"'
Your filter can be directly a function or a filter name. Here a plunkr

How to start editing new row/column added to grid immediately

I'm working on a small application where I want to add a new row to a single-column EditorGridPanel, and each time a new row is added I want it to be in edit mode so the user can write the wanted text into it immediately.
Relevant code from a complete jsfiddle:
store = new Ext.data.ArrayStore({
autoDestroy: true,
storeId: 'myStore',
idIndex: 0,
fields: [
{ name: 'group', type: 'string' }
],
data: [],
listeners: {
add: function(t, records, index) {
// This call causes problems
grid.startEditing(index, 0);
}
}
});
When the add event in the store is triggered, which should be after the record has been added, it seems it still hasn't been added to the actual grid, only the store. This causes an error in in the grid component.
Is there any other event, possibly in the grid component, that can be used instead?
This is just a matter of timing. You are trying to add the grid when you add the record to the store and it takes a little time for the two things to be in sync. You should try putting your code on the rowinserted event handler of the grid.getView() .
For your code to work the way you have it right now, simply change it to:
store = new Ext.data.ArrayStore({
autoDestroy: true,
storeId: 'myStore',
idIndex: 0,
fields: [
{ name: 'group', type: 'string' }
],
data: [],
listeners: {
add: function(t, records, index) {
Ext.defer(function() {
grid.startEditing(index, 0);
},10);
}
}
});
Doing this will give enough time for the info between the store and the grid to be in sync.

ExtJS - Creating hyperlinks with a function

I'm trying to build an edit column, but my routine isn't quite right for some reason. My value of "store" is not returning anything like I thought it would.
Any thoughts?
function editLinkRenderer(value, metadata, record, rowIndex, colIndex, store) {
if (store == V2020.ServiceStore)
return 'Edit';
else if (store == V2020.PriceStore)
return 'Edit';
else if (store == V2020.PromoStore)
return 'Edit';
return "Edit";
}
I'm using it in my gridpanel like so:
{ header: "Edit", width: 60, dataIndex: 'serviceID', sortable: false, renderer: editLinkRenderer },
You might consider using an ActionColumn. That way you can do this:
var items = [ ... ]; // existing items
if (store.constructEditColumn) {
items.push(store.constructEditColumn());
}
Where your constructEditColumn might look like this:
...
constructEditColumn: function() {
return {
xtype: 'actioncolumn',
items: {
text: 'Edit',
handler: function() {
// do stuff
},
scope: this
}
}
},
...
Barring that, I'd be suspicious of doing equality on the stores. Are the two params before store ints? Can you breakpoint and take a look at whether the record.store property is what you expect? Old version of Ext, perhaps, with a different signature to the renderer?
I appreciate you taking a look, but I figured out the issue.
I had two V2020.ServiceStore defined by mistake and the latter one was mucking everything up.

EXTJS + Updating a store with the database ID after saving a grid

I'm trying to learn how to use the EXTJS grids for some simple CRUD operations over a table in a admin app.
I have a simple grid that allows someone to edit users, the store is defined as:
var userDataStore = new Ext.data.Store({
id: 'userDataStore',
autoSave: false,
batch: true,
proxy: new Ext.data.HttpProxy({
api: {
read: '/Admin/Users/All',
create: '/Admin/Users/Save',
update: '/Admin/Users/Save'
}
}),
reader: new Ext.data.JsonReader(
{
root: 'Data',
idProperty: 'ID',
totalProperty: 'total',
successProperty: 'success',
messageProperty: 'message'
}, [
{ name: 'ID', type: 'string', allowBlanks: false },
{ name: 'NT_ID', type: 'string', allowBlank: false },
{ name: 'EMail', type: 'string', allowBlank: false },
{ name: 'Name', type: 'string', allowBlank: false },
{ name: 'Enabled', type: 'bool', allowBlank: false },
{ name: 'CurrentRoleCode', type: 'string', allowBlank: false}]
),
writer: new Ext.data.JsonWriter(
{
encode: false,
writeAllFields: true,
listful: true
})
});
This is bound to a grid, and I am able to load and save users without issue. The save button looks like this:
var saveButton = new Ext.Button({
text: 'Save',
disabled: true,
handler: function() {
userDataStore.save();
pageState.ClearDirty();
saveButton.disable();
}
});
However, when creating a new user, the JSON POST for the user is posted to the same REST service end point as "Update", with the only difference being that no ID value is posted (as one is only set in the store when loading from the server).
This works, and I am able to create users.
The save REST service emits back the created row with the new database ID, and I was under the assumption that EXTJS would automatically bind the new generated database ID to the row. This allows the user to further edit that row, and cause an update instead of a insert.
Instead, the row continues to have a blank user ID, so an additional save creates another new user.
So either:
EXTJS is supposed to resolve generated row ID's automatically and I am just doing something wrong.
I am supposed to manually reload the grid after each save with an additional REST call.
I've been looking at EXTJS documentation and forums, but I am unclear on the proper approach.
Can someone clarify?
EDIT: I tried returning Success = True in JSON to match the SuccessProperty, however this still didn't seem to work.
EDIT #2: So far the only thing I've found that works is doing "userDataStore.reload()" after saving, however because I was returning the contents of the store back after saving, I was hoping that EXTJS would understand that and update the row values.
I've got an idea that may help you. Let't suppose that user added a new
record in grid, in that moment add a new property newRecOrderNo to the record to
identify the record after response. When user will post data to server after
inserting you must get a new ID and associate it to newRecOrderNo
(like Map<Integer,Integer>). Then return json object like that :
{
success : true,
newIdes : {
1 : 23,
2 : 34
}
}
Then when you get response do set proper IDs to records:
userDataStore.each(function(rec){
if(rec.data.newRecOrderNo){
rec.data.ID = response.newIdes[rec.data.newRecOrderNo];
delete rec.data.newRedOrderNo;
}
})
})
Yes, it sets id (and also other fields, if server returns modified values of them), if create ajax backend returns record with set id, at least in extjs 4.1. You should return inserted record, with id set, under 'root' key as json dictionary, in this example root is 'Data', i.e.:
{
"Data": {
"ID": 8932,
"NT_ID": 28738273,
...
"CurrentRoleCode": "aaa",
},
"success": true
}
You need reload store with new params in savebtn handler
like
store.reload();
of course you can add more params to load action

Categories

Resources