ExtJs4 to ExtJs5 Upgrade: GroupedColumn Chart is not working - extjs

I am new to Extjs5. I am upgrading extJs4 to ExtJs 5. I am trying to implement a groupedColumn chart but no data shows up only the axises are visible. Even I am not getting any error.
My code is as follows:
Ext.define('Result', {
extend: 'Ext.data.Model',
fields: [
{ name: 'state', type: 'string', mapping:0 },
{ name: 'product', type: 'string', mapping:1 },
{ name: 'quantity', type: 'int', mapping:2 }
]
});
var store = Ext.create('Ext.data.ArrayStore', {
model: 'Result',
groupField: 'state',
data: [
['MO','Product 1',50],
['MO','Product 2',75],
['MO','Product 3',25],
['MO','Product 4',125],
['CA','Product 1',50],
['CA','Product 2',100],
['WY','Product 1',250],
['WY','Product 2',25],
['WY','Product 3',125],
['WY','Product 4',175]
]
});
Ext.define('Ext.chart.series.AutoGroupedColumn', {
extend: 'Ext.chart.series.Bar',
type: 'autogroupedcolumn',
alias: 'series.autogroupedcolumn',
gField: null,
constructor: function( config ) {
this.callParent( arguments );
// apply any additional config supplied for this extender
Ext.apply( this, config );
var me = this,
store = me.chart.getStore(),
// get groups from store (make sure store is grouped)
groups = store.isGrouped() ? store.getGroups().items : [],
// collect all unique values for the new grouping field
groupers = store.collect( me.gField ),
// blank array to hold our new field definitions (based on groupers collected from store)
cmpFields = [];
// first off, we want the xField to be a part of our new Model definition, so add it first
cmpFields.push( {name: me.xField } );
// now loop over the groupers (unique values from our store which match the gField)
/* for( var i in groupers ) {
// for each value, add a field definition...this will give us the flat, in-record column for each group
cmpFields.push( { name: groupers[i], type: 'int' } );
}*/
for (var i = 0; i < groupers.length; i++) {
var name = groupers[i];
cmpFields.push({name:name,type:'number'});
}
// let's create a new Model definition, based on what we determined above
Ext.define('GroupedResult', {
extend: 'Ext.data.Model',
fields: cmpFields
});
// now create a new store using our new model
var newStore = Ext.create('Ext.data.Store', {
model: 'GroupedResult'
});
// now for the money-maker; loop over the current groups in our store
for( var i = 0; i < groups.length; i++ ) {
// get a sample model from the group
var curModel = groups[ i ].items[ 0 ];
// create a new instance of our new Model
var newModel = Ext.create('GroupedResult');
// set the property in the model that corresponds to our xField config
newModel.set( me.xField, curModel.get( me.xField ) );
// now loop over each of the records within the old store's current group
for( var x = 0; x < groups[ i ].items.length; x++) {
// get the record
var dataModel = groups[ i ].items[ x ];
// get the property and value that correspond to gField AND yField
var dataProperty = dataModel.get( me.gField );
var dataValue = dataModel.get( me.yField );
// update the value for the property in the Model instance
newModel.set( dataProperty, dataValue );
// add the Model instance to the new Store
newStore.add( newModel );
}
}
// now we have to fix the axes so they work
// for each axes...
me.chart.axes.every( function( item, index, len ) {
// if array of fields
if( typeof item.getFields()=='object' ) {
// loop over the axis' fields
for( var i in item.fields ) {
// if the field matches the yField config, remove the old field and replace with the grouping fields
if( item.getFields(i)==me.yField ) {
Ext.Array.erase( item.getFields(), i, 1 );
Ext.Array.insert( item.getFields(), i, groupers );
break;
}
}
}
// if simple string
else {
// if field matches the yField config, overwrite with grouping fields (string or array)
if( item.getFields()==me.yField ) {
item.setFields(groupers);
}
}
});
// set series fields and yField config to the new groupers
me.fields,me.yField = groupers;
// update chart's store config, and re-bind the store
me.chart.store = newStore;
me.chart.bindStore( me.chart.store, true );
// done!
}
})
Ext.create('Ext.chart.CartesianChart', {
renderTo: Ext.getBody(),
width: 500,
height: 300,
animate: true,
store: store,
legend: {
position: 'right'
},
axes: [
{
type: 'numeric',
position: 'left',
fields: ['quantity'],
label: {
renderer: Ext.util.Format.numberRenderer('0,0')
},
title: 'Quantity',
grid: true,
minimum: 0
},
{
type: 'category',
position: 'bottom',
fields: ['state'],
title: 'State'
}
],
series: [
{
type: 'autogroupedcolumn',
axis: 'left',
highlight: true,
xField: 'state',
yField: 'quantity',
gField: 'product'
}
]
});
I have used Ext.chart.series.Bar in place of Ext.chart.series.Column as Ext.chart.series.Column no more valid in ExtJs 5. I also have made other minor essential changes required to make my code compatible to ExtJs 5. You can also check this example on https://fiddle.sencha.com/#fiddle/hvk .
I have already spent 3 days on it. Please help!! Thanks in advance.

#Samir, If you want a Grouped Chart which is non-stacked use stacked: false property in series. Modify the code of #MonicaOlejniczak as:
legend :{
docked: right
}
series: {
.......
........
stacked: false,
}
This should solve your problem.

Related

Position a specific row of a grid as the first row

How to set a particular row in grid as the first row in the grid I have tried selecting the row as shown below
var grid = interface.down('directorReviewGrid');
store.removeAll();
store.load({
params: {
workflow_stage: workflow_stage
},
callback: function(records, operation, success) {
var rowIndex = this.find('id', id);
/*where 'id': the id field of your model,
record.getId() is the method automatically created by Extjs.
You can replace 'id' with your unique field.. And 'this' is your store.*/
grid.getView().scrollRowIntoView(rowIndex);
grid.getView().select(rowIndex);
}
});
You can implement using store.insert( 0, records ) and for go to particular that, you can use grid.getView().focusRow(rowIdx).
You can check in this working FIDDLE. Hope this will help/guide you to achieve your requirement.
CODE SNIPPET
var char = 'ABCDEFGHJKLIMNOPQRSTUVWXYZ';
function getRandomNumber() {
return Math.floor(Math.random() * 26);
}
function getRandomName() {
let name = '';
for (let i = 0; i < 6; i++) {
name += char.charAt(getRandomNumber());
}
return name;
}
function getData() {
let data = [];
for (let key = 0; key < 100; key++) {
data.push({
id: key,
name: getRandomName()
})
}
return data
}
Ext.create('Ext.data.Store', {
storeId: 'gridstore',
fields: ['id', 'name'],
data: getData()
});
Ext.create('Ext.grid.Panel', {
title: 'Focus to Row',
store: 'gridstore',
columns: [{
text: 'ID',
dataIndex: 'id'
}, {
text: 'Name',
dataIndex: 'name',
flex: 1
}],
height: window.innerHeight,
renderTo: Ext.getBody(),
tbar: ['->', {
text: 'Move Selected Row to First',
handler: function () {
var grid = this.up('grid'),
store = grid.getStore(),
selctionM = grid.getSelectionModel(),
rec = selctionM.getSelection()[0];
//If selected record is available
if (rec) {
store.remove(rec) //First the remove the store
store.insert(0, rec); //Insert into 1st postion
selctionM.select(rec); //Select same record
grid.getView().focusRow(rec); //Focuses a particular row and brings it into view. Will fire the rowfocus event.
} else {
Ext.Msg.alert('Info', 'Please select any row');
}
}
}]
});

Extjs Combobox store value from another object

I have a object that has some values that i want to display in a combobox that i am adding to a form panel inside a for loop.
this is the contents of the object object
but in my combobox i get data as [object Object]
here is what i am currently doing
for(var i = 0; i < data.length ; i++)
{
console.log('ad');
var storeStates = new Ext.data.ArrayStore({
fields: ['optionText'],
data : [data[i].data.selectOptions.list[i].optionText]
});
var cb = new Ext.form.ComboBox({
fieldLabel: data[i].data.name,
hiddenName: 'fieldTypeName',
id: data[i].data.name.toString(),
valueField: 'optionText',
displayField: 'optionText',
typeAhead: true,
allowBlank: false,
mode: 'local',
selectOnFocus: true,
triggerAction: 'all',
emptyText: 'Survey Field Type',
disabled: this.existingField,
width: 190,
store: storeStates,
listeners: {
'select': function (combo, newValue, oldValue) {
}
}
});
Ext.getCmp('survey-field-form').add(cb);
//Ext.getCmp('survey-field-form').doLayout();
console.log('added');
}
You need to change your store definition from Ext.data.ArrayStore to Ext.data.Store & data as data[i].data.selectOptions.list
var storeStates = new Ext.data.Store({
fields: ['optionText'],
data : data[i].data.selectOptions.list
});
I think you need to define your store like that to get the correct display:
var storeStates = new Ext.data.JsonStore({
data: data[i].data.selectOptions.list,
fields: [{name: "optionText", type: "string"}]
});
I solved it by creating a reader and a store and pushing data into the store and then loading the store like this
// create a Record constructor:
var rt = Ext.data.Record.create([
{name: 'optionValue'},
{name: 'optionText'}
]);
var myStore = new Ext.data.Store({
// explicitly create reader
reader: new Ext.data.ArrayReader(
{
idIndex: 0 // id for each record will be the first element
},
rt // recordType
)
});
var myData = [];
for(var j = 0; j < data[i].data.selectOptions.list.length; j++)
{
var optionText = data[i].data.selectOptions.list[j].optionText.toString();
var optionValue = data[i].data.selectOptions.list[j].optionValue.toString();
myData.push([optionValue, optionText]);
}
myStore.loadData(myData);
Hope this helps someone else

Preselect items in EXT JS 4.2 Grid

I am trying to preselect items in my EXT grid based on the value of one of the items in the data store.
In my data store I fetch 7 items, the last item I grab 'installed' is a BOOLEAN and I would like to use that to preselect items in my grid.
Here is the code I have so far that is not working...
Ext.require([
'Ext.grid.*',
'Ext.data.*',
'Ext.selection.CheckboxModel'
]);
Ext.onReady(function(){
Ext.QuickTips.init();
var sb = $('#sb_id').val();
// Data store
var data = Ext.create('Ext.data.JsonStore', {
autoLoad: true,
fields: [ 'name', 'market', 'expertise', 'id', 'isFull', 'isPrimary', 'installed'],
proxy: {
type: 'ajax',
url: '/opsLibrary/getLibraryJsonEdit',
extraParams: {
sb_id: sb
},
actionMethods: 'POST'
},
sorters: [{
property: 'market',
direction: 'ASC'
}, {
property: 'expertise',
direction: 'ASC'
}]
});
data.on('load',function(records){
Ext.each(records,function(record){
var recs = [];
Ext.each(record, function(item, index){
console.log(item.data);
if (item.data['installed'] == true) {
console.log('Hi!');
recs.push(index);
}
});
//data.getSelectionModel().selectRows(recs);
})
});
// Selection model
var selModel = Ext.create('Ext.selection.CheckboxModel', {
columns: [
{xtype : 'checkcolumn', text : 'Active', dataIndex : 'id'}
],
listeners: {
selectionchange: function(value, meta, record, row, rowIndex, colIndex){
var selectedRecords = grid4.getSelectionModel().getSelection();
var selectedParams = [];
// Clear input and reset vars
$('#selected-libraries').empty();
var record = null;
var isFull = null;
var isPrimary = null;
// Loop through selected records
for(var i = 0, len = selectedRecords.length; i < len; i++){
record = selectedRecords[i];
// Is full library checked?
isFull = record.get('isFull');
// Is this primary library?
isPrimary = record.get('isPrimary');
// Build data object
selectedParams.push({
id: record.getId(),
full: isFull,
primary: isPrimary
});
}
// JSON encode object and set hidden input
$('#selected-libraries').val(JSON.stringify(selectedParams));
}}
});
I was trying to use an on.load method once the store was populated to go back and preselect my items but am not having any luck.
Im a Python guy and don't get around JS too much so sorry for the noobness.
Any help would be appreciated.
Thanks again!
You should be able to do something like:
//create selModel instance above
data.on('load', function(st, recs) {
var installedRecords = Ext.Array.filter(recs, function(rec) {
return rec.get('installed');
});
//selModel instance
selModel.select(installedRecords);
});
Select can take an array of records.
http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.selection.Model-method-select
//data.getSelectionModel().selectRows(recs);
Didn't work because store's don't have a reference to selection models it is the other way around. You can get a selection model from a grid by doing grid.getSelectionModel() or
you can just use the selModel instance you created
var selModel = Ext.create('Ext.selection.CheckboxModel', {

How to remove field in websql

I have created a table in my websql using Sencha. Adding values to table works fine,
but removing doesn't work.
I've tried
getStore('favorite').removeAt(1);
but it gave no result. Are there are ways to handle sql requests like
"Delete from favorite where id = 1"
I've been Googling all day long. Any ideas? the code is below:
dockedItems: [
{
xtype: 'toolbar',
dock: 'top',
items: [
{
text: '+',
ui: 'decline',
handler: function(){
var s_name = post.get('list');
var s_image = post.get('image');
//var s_type = record.get('code');
//var c_content = post.get('filmpage');
//alert('РаботаетЬ');
Ext.require(['Ext.data.proxy.SQL']);
Ext.define("Favorite", {
extend: "Ext.data.Model",
config: {
fields: ["id","name","ftype","image","link","res"]
}
});
Ext.create("Ext.data.Store", {
model: "Favorite",
storeId: 'Favorite',
proxy: {
type: "sql"
}
});
var store = Ext.getStore('Favorite');
Ext.getStore('Favorite').removeAt(1);
Ext.getStore('Favorite').sync();
var record = Ext.getStore('Favorite').findExact('id', 1);
Ext.getStore('Favorite').remove(record);
Ext.getStore('Favorite').sync();
/*Ext.getStore('Favorite').add([{
name: s_name,
ftype: cat,
image: s_image,
link: '',
res : '',
}]);
Ext.getStore('Favorite').sync();*/
//Ext.getStore("Users").getModel("Users").getProxy("Users").dropTable("Favorite");
//Ext.getStore("Favorite").getModel("Ext.data.Model").getProxy().dropTable();
}
}
]
}
]
find solution using js that works, still thank you very much for your help.
db = openDatabase("Sencha", "1.0", "Sencha", 200000);
if(!db)
alert("Failed to connect to database.");
else
alert('yeah');
db.transaction(function(tx) {
tx.executeSql("DELETE FROM Favorite WhERE id = 3 ", [], function(result){}, function(tx, error){});
});
You should sync after removing record
var store = Ext.getStore('favorite');
store.removeAt(1);
store.sync();
Update
var index = store.findExact('id', 1);
store.remove(store.getAt(index));
store.sync();
How to debug
console.log(index); // Should return value 0 if there is a match else returns -1.
console.log(store.getAt(index)); // Should return the record with id value 1.

Extjs Grid - Delete all record has a conditional

I have a grid and a button will delete in http://jsfiddle.net/9zB8R/
My field like fields: ['id', 'name', 'type']. If type == delete i will delete it.
I init data like:
var simpleData = [];
var store = new Ext.data.ArrayStore({
fields: ['id', 'name', 'type'],
data: simpleData
});
for (i = 0; i < 20; i++) {
simpleData.push({id:''+i+'', name: 'name'+i, type: 'delete'});
}
//this record will not delete
simpleData.push({id:'20', name: 'enable', type: 'enable'});
store.loadData(simpleData);
I have a tbar like below but that can't delete all record have type == delete. How can i fix that. Thanks.
tbar:[
{
text:'Delete all type = delete',
handler:function(){
store.each(function(item, idx) {
if (item && item.get('type')=='delete') {
store.removeAt(idx);
}
});
}
}
]
The problem is with the "each" loop. Removing items in the loop is changing store size and hence only some of the items are getting deleted.
To get around it, you can loop through the store in reverse order and then delete as below:
var grid = new Ext.grid.GridPanel({
width: 400,
height: 600,
store: store,
loadMask: true,
renderTo: Ext.getBody(),
tbar:[
{
text:'Delete all type = delete',
handler:function(){
var i = store.getCount()-1;
for (i; i>=0; i--) {
if (store.getAt(i).get('type')=='delete') {
store.removeAt(i);
}
}
}
}
],

Resources