ExtJS: Converting model columns to rows in a grid - javascript

I'm very new to ExtJS and wanted to achieve the following:
I have a model with data something like this:
{
"Account_Enabled": true,
"Requirements_gathered": true,
"work_done": false,
"deadlines": {
"Account_Enabled": true,
"Requirements_gathered": false
}
}
There are no multiple rows. Only a single row returned from the database.
I want to display the data in a grid with three columns
Column1: The name of the column
Column2: A checkbox that shows whether the value is true or false
Column3: A checkbox that shows whether the column name present in "deadlines" or not
Ex:
Account_Enabled True True
Requirements_Gathered True False
work_done False Undefined(Checkbox need to be disabled)
Basically, i need to convert that single row into three columns.
Also, i need to the update the store when the user checks/uncheks the checkboxes
May i know if there is any way to achieve this via ExtJS grids? or is there any better idea?
Thanks in advance

There is no direct way to bind your json response in the format you mention to the grid store.
What you need to do is to manipulate the response the match grid columns required.
Check this working example ExtJs Fiddle
//Your Original Response
let response = '{"Account_Enabled": true, "Requirements_gathered": true, "work_done": false, "deadlines": {"Account_Enabled": true, "Requirements_gathered": false}}';
// Convert your response to object
let jsonDecode = Ext.decode(response);
//This function to convert your response to match grid store
let dataConvert = function(jsonObj){
//Returned array object
let data = [];
// To get Object of deadlines and know if the property exist or not
let availableData = jsonObj.deadlines
//Loop throw object property
for(var objProperty in jsonObj){
//Ignore deadlines property
if(objProperty=="deadlines"){
continue;
}
//Adding the object to the array "objPropery" will return the property name
//"jsonObj[objProperty]" will return the value of property if it is true or flase
//"availableData[objProperty]" will return the value if exist in availableData
data.push({colName:objProperty,isReqGathered:jsonObj[objProperty],isWorkDone:availableData[objProperty]})
}
return data
}
let gridStore = Ext.create('Ext.data.Store', {
storeId: 'gridStoreId',
fields: ['colName', 'isReqGathered', 'isWorkDone'],
data: dataConvert(jsonDecode)
});
Ext.create('Ext.grid.Panel', {
title: 'Test Store Filter',
width: 500,
height: 400,
renderTo: Ext.getBody(),
store: gridStore,
columns: [{
dataIndex: 'colName',
text: 'colName'
}, {
dataIndex: 'isReqGathered',
text: 'isReqGathered'
}, {
dataIndex: 'isWorkDone',
text: 'isWorkDone'
}]
})

Related

In xtype tagfield, the values sent to the server appear as a single combined line. Extjs

In the Ext.form.Panel component, I use the field:
....
{
xtype: 'tagfield',
fieldLabel: 'Установить сотрудников',
name: 'survey_users',
store: {
type: 'usertreestore'
},
reference: 'UserTreeStore',
displayField: 'text',
valueField: 'id',
filterPickList: true,
queryMode: 'remote',
publishes: 'value'
},
....
I set the values for this field and send it to the update in the store.
The value of the field survey_users looks like one combined string "survey_users": 469473475463
but the right kind of values is 469,473,475,463
Below is the full form data when you submit.
[{"text":"\u0414\u0430\u0432\u044b\u0434\u043e\u0432 \u0410\u043b\u0435\u043a\u0441\u0435\u0439","id":"75","survey_users":469473475463,"survey_cofficient":2,"parentId":"73"}]
In the controller, the save method looks like this:
...
saveUserData: function(button, e) {
var values;
var form = button.up('form');
record = form.getRecord();
store = this.getUserTreeStoreStore('UserTreeStore');
values = form.getValues();
id = form.getRecord().get('id');
values.id=id;
record.set(values);
console.log(record)
store.sync();
},
...
Before setting the values ​​in the record, it is clear that the values ​​are and they are in the correct format, but after setting the values ​​in the record field survey_users: NaN
I bring a screen output in the console
How to make sure that when submitting a form, the values of the survey_users field were sent in the correct format?
Try encodeSubmitValue
Here's the FIDDLE
Network:

How to render a form in a grid row

I'm trying to render a form within a custom row grid without success.
handler: function (button, record, pressed, eOpts) {
var grid = this.up('grid');
var store = grid.getStore();
var innerPanel = Ext.widget('form', {
//renderTo: record,
title: 'Title Test',
name: 'test',
items: [{
xtype: "textfield",
name: "testfield",
fieldLabel: "FooTest"
}]
});
// store.add(record);
store.add(innerPanel);
}
Any idea how to do this?
Fiddle: https://fiddle.sencha.com/#fiddle/183e
Thanks.
EDITED with taubi19 sugestion.
I think you don't quite understand the concepts yet. The form is a part of the view, the store is an object, that takes care of the data. You want to have a column in which each row is a form. This means you need a column whose xtype is not textfield, but something custom. I found out on senchas kitchen sink, that we need a 'widgetcolumn ' . In your fiddle, change the columns array with the following code and you will have a form in each new row.
columns:[
{
header:'Name',
dataIndex:'name',
flex:1,
xtype:'widgetcolumn',
widget:{
width:400,
xtype:'form',
items:[
{
xtype:"textfield",
name:"testfield",
fieldLabel:"FooTest"
},
{
xtype:"textfield",
name:"testfield1",
fieldLabel:"FooTest1"
}
]
}
}
]
And I suggest you remove adding the form to the store. You add records/data to stores. The store.add method takes a model instance as a parameter (Ext.data.Store.add).

Angular with Kendo, Using Grid Values Asynchronously

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!

ExtJS 4, customize boolean column value of Ext.grid.Panel

Good day, i have a grid with boolean column:
var grid = Ext.create('Ext.grid.Panel', {
...
columns: [{
dataIndex: 'visibleForUser',
text: 'Visible',
editor: {
xtype: 'checkboxfield',
inputValue: 1 // <-- this option has no effect
}
},
...
Grid's store is remote via JSON proxy. When i save or update row, the resulting JSON
look like:
{... visibleForUser: false, ... }
As you see, ExtJS serializes checkbox value as true or false JSON terms.
I need to customize this and serialize to, say, 1 and 0, any suggestion how to accomplish this ? Thank you.
I've just changed my checkboxes system-wide to always act/respond to 0 and 1:
Ext.onReady(function(){
// Set the values of checkboxes to 1 (true) or 0 (false),
// so they work with json and SQL's BOOL field type
Ext.override(Ext.form.field.Checkbox, {
inputValue: '1',
uncheckedValue: '0'
});
});
But you can just add this configs per checkbox.
Ext JS 4.1.1 has a new serialize config on record fields. When a writer is preparing the record data, the serialize method is called to produce the output value instead of just taking the actual field value. So you could do something like this:
fields: [{
name: "visibleForUser",
type: "boolean",
serialize: function(v){
return v ? 1 : 0;
}
/* other fields */
}]
I try to avoid overriding default component behavior whenever possible. As I mentioned, this only works in 4.1.1 (it was introduced in 4.1.0 but I believe it was broken). So if you're using an earlier version, one of the other answers would suit you better.
You can try to override getValue
Ext.define('Ext.form.field.Checkbox', {
override : 'Ext.form.field.Checkbox',
getValue: function () {
return this.checked ? 1 : 0;
}
});

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