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

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;
}
});

Related

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!

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

Kendo Grid filtering using 2 decimal places when DataSource data uses 4 decimals

I have a Kendo Grid displaying dollar amounts but the data in the DataSource returns 4 decimal places.
The DataSource data looks something like this:
{ totalDollars: 1513.1548 },
{ totalDollars: 158.2903 },
{ ... }
So to display the number correctly I use the column format...
columns: [
{ field: 'totalDollars', format: '{0:c2}' },
{ ... }
]
But now I want to filter this column. If I filter with "Is Equal To" 159.29 it fails.
I've made it work using 4 decimals and using column.filterable.ui:
columns: [
{
field: 'totalDollars',
format: '{0:c2}',
filterable: {
ui: function(e) {
element.kendoNumericTextBox({
format: "n4",
decimals: 4
});
}
}
}
]
But this doesn't help because the user doesn't know the last 2 decimals. So I need it to only use up to 2 decimals when filtering.
Is this possible?
JSFiddle here - note that filtering by "Mono Cost" using 7133.03 doesn't work but 7133.0332 does. I'm looking to make 7133.03 work.
I have updated the fiddle for you http://jsfiddle.net/53pqe3mo/2/
But essentially you can override the default parser for the value being returned by adding the following:
DefaultMonoCPP: {
editable: false,
type: "number",
parse: function(e)
{
console.log(e);
return kendo.parseFloat(kendo.toString(e,"c2"));
}
I have added the console.log line just to show you that the value actually being passed in is the original supplied by the datasource.
It took a little finding but this link should help:
http://docs.telerik.com/kendo-ui/api/javascript/data/model#methods-Model.define
edit:
updated answer based on comments.
for future reference use this link:
http://docs.telerik.com/kendo-ui/framework/globalization/numberparsing

Can't sort Features by User Story Count in Grid

EDIT: ANSWER FOUND
I found the answer in this post. there is a private store config field called remoteSort that is set to true by default, so client-side sorters won't get used unless remoteSort is explicitly set to false.
I'm trying to sort a grid of Features by the number of User Stories in them. I've tried a couple different things. The first was a sorter function in the data Store Configuration:
Ext.create('Rally.data.wsapi.Store',{
model: 'PortfolioItem/Feature',
autoLoad:true,
start: 0,
pageSize: 20,
fetch: ['Name', 'ObjectID', 'Project', 'Release', 'UserStories','State','_ref'],
context://context stuff
filters:[
//filter stuff
],
sorters:[
{
property:'UserStories',
sorterFn: function(o1, o2){
return o1.get('UserStories').Count - o2.get('UserStories').Count;
}
}
],
listeners: //listener stuff
But this always returned nothing. (when the sorter was not included, i did get back all the Correct Features, but I could not sort the the number of user stories per Feature).
I also tried adding a sorter to the column in the grid, as seen in this post:
xtype: 'rallygrid',
width:'50%',
height:400,
scroll:'vertical',
columnCfgs: [
{
text:'Stories',
dataIndex:'UserStories',
xtype:'numbercolumn',
sortable:true,
doSort: function(direction){
var ds = this.up('grid').getStore();
var field = this.getSortParam();
console.log(ds, field, direction);
ds.sort({
property: field,
direction:direction,
sorterFn: function(us1, us2){
return (direction=='ASC'? 1 : -1) * (us1.get(field).Count - us2.get(field).Count);
}
});
},
width:'20%',
renderer:function(us){
return us.Count;
}
}
]
But I was having the same issues that the person in the other thread was having, where nothing was getting sorted.

Extjs 4 gridrow draws blank after model save

I have a couple of grids, divided in an accordion layout. They basicly show the same kind of data so an grouped grid should do the trick, however it looks really good this way and so far it works good too.
Left of the grids there is a form panel which is used to edit grid records, when I click on a record in the grid the appropriate data shows up in the form. I can edit the data, but when I click the save button, which triggers an 'model'.save() action, the related grid row draws blank and a dirty flag appears. I checked the model and the 'data' attribute doesn't contain any data but the id, the data is present in the 'modified' attribute.
I read that the red dirty flag means that the data isn't persisted in the back-end, but in this case it is. The request returns with a 200 status code and success : true.
The onSave method from the controller:
onSave : function() {
// Get reference to the form
var stepForm = this.getStepForm();
this.activeRecord.set( stepForm.getForm().getValues() );
this.activeRecord.save();
console.log( this.activeRecord );
}
The step store:
Ext.define( 'Bedrijfsplan.store.Steps', {
extend : 'Ext.data.Store',
require : 'Bedrijfsplan.model.Step',
model : 'Bedrijfsplan.model.Step',
autoSync : true,
proxy : {
type : 'rest',
url : 'steps',
reader : {
type : 'json',
root : 'steps'
},
writer : {
type : 'json',
writeAllFields : false,
root : 'steps'
}
}
} );
Step model:
Ext.define( 'Bedrijfsplan.model.Step', {
extend : 'Ext.data.Model',
fields : [ 'id', 'section_id', 'title', 'information', 'content', 'feedback' ],
proxy : {
type : 'rest',
url : 'steps',
successProperty : 'success'
}
} );
Step grid
Ext.define( 'Bedrijfsplan.view.step.Grid', {
extend : 'Ext.grid.Panel',
alias : 'widget.stepsgrid',
hideHeaders : true,
border : false,
columns : [ {
header : 'Titel',
dataIndex : 'title',
flex : 1
} ]
} );
I spend a couple of hours searching and trying, but I still haven't found the solution. Some help on this matter would be appreciated :)
Your model updating code:
this.activeRecord.set( stepForm.getForm().getValues() );
Should work, but I might try splitting it into two lines and setting a breakpoint to verify that getValues() is returning what you're expecting.
Also ensure that you have the name attribute set for each field in your form and that it matches exactly to the names of fields in your model.
Finally, it's better to call .sync() on the store rather than .save() on the model when you're working with a model that belongs to a store. They option autoSync: true on the store will make this happen automatically each time you make a valid update to one of its models.
The BasicForm.loadRecord and BasicForm.updateRecord methods provide a nice wrapper around the functionality you're seeking that may work better:
onRowSelected: function(activeRecord) {
stepForm.getForm().loadRecord(activeRecord);
}
onSaveClick: function() {
var activeRecord = stepForm.getForm().getRecord();
stepForm.getForm().updateRecord(activeRecord);
activeRecord.store.sync();
}
The only oddity I see is with your: this.activeRecord.set( stepForm.getForm().getValues() );
I've always used .set() on the store never on the record. e.g.:
myDataStore.set( stepForm.getForm().getValues() );

Categories

Resources