EXTJS Pass data to another JS store - extjs

I am new to EXTJS. I am developing application using EXTJS 4.2. I have grid that shows list of Unix server details. I have 2 JS one is serverdetails.js that shows all the servers in the grid and another one is pie.js that shows pie chart. My requirement is when I select server from the grid that is in ServerDetails.js and click on button it goes to dao layer to get server details, Now this server details I have to passed on to Pie chart Js Ext.data.Store object. How do I pass these server details to Pie chart JS?
Below is my code.
On the grid I have dashboard button that shows the pie chart for selected row in the grid. below is the code for that.
showDashBoard : function(button) {
var grid = Ext.ComponentQuery.query('serverdetailslist')[0];
var sm = grid.getSelectionModel();
var rs = sm.getSelection();
if (!rs.length) {
Ext.Msg.alert('Info', 'No Server Details Selected');
return;
}else{
dashBoardServerDetail = rs[0].getData();
var url = '/TechnologyTrackPortal/dashboard/loadDashBoard.action';
Ext.Ajax.request({
url : url,
method : 'POST',
jsonData: dashBoardServerDetail,
success: function(response){
var iResult = response.responseText;
Ext.create('resources.script.Pie');
}
});
}
}
response.responseText give me data in jason format. Now how do I pass this jason dat to pie.js file. Below is my pie.js file
Ext.onReady(function () {
Ext.define('DashBoardModel', {
extend: 'Ext.data.Model',
fields: [
{name: 'title', type: 'string'},
{name: 'size', type: 'string'}
]
});
var store = Ext.create('Ext.data.Store', {
storeId : 'DashBoardStoreId',
model : 'DashBoardModel',
fields : ['title', 'size'],
autoLoad: false,
autoSync: true
});
var chart = Ext.create('Ext.chart.Chart', {
alias : 'widget.dashBoardPieChart',
title : 'Technology Portal',
store : store,
theme: 'Base:gradients',
legend: {
position: 'bottom'
},
series: [
{
type: 'pie',
angleField: 'size',
showInLegend: true,
label: {
field: 'title',
display: 'outside',
font: '12px Arial',
calloutLine: true
},
highlight: {
segment: {
margin: 20
}
},
label: {
field: 'title',
display: 'rotate',
contrast: true,
font: '18px Arial'
},
tips: {
trackMouse: true,
width: 120,
renderer: function(storeItem, item) {
this.setTitle(storeItem.get('title') + ': ' + storeItem.get('size') + '%');
}
}
}
]
});
var panel1= Ext.create('widget.panel', {
// extend : 'widget.panel',
width: 800,
height: 600,
title: 'Server',
alias : 'widget.dashBoardForm',
renderTo: Ext.getBody(),
layout: 'fit',
tbar: [{
text: 'Save Chart',
handler: function() {
Ext.MessageBox.confirm('Confirm Download', 'Would you like to download the chart as an image?', function(choice){
if(choice == 'yes'){
chart.save({
type: 'image/png'
});
}
});
}
}],
items: chart
});
I hope I am clear with my points.
Thanks
Sach

You need to see this as one app, one memoryspace, that the code is separated in two .js files makes not much difference, they both have to be loaded in your main html, asp, php or whatever. In that memoryspace you can reference each others variables and objects if they were declared before. The easiest way to accomplish what you ask is to have one store and use that for both views. So load the data in the store in your ServerDetails.js and have the chart use this same store.
I have some ExtJs apps that do that but they are for version 3.3.1 and not at my disposal for the moment. Hope this helps.

Related

Read text file into the text area in extjs

I have mail.txt on my local machine and i want to display it on the UI using extjs. I created a textarea and want to import mail.txt into it.
Ext.define('com.company.view.dashboard.Dashboard', {
extend: 'Ext.panel.Panel',
alias: 'widget.dashboard',
layout: 'fit',
iconCls: 'dashboard-tree',
initComponent: function(config) {
Ext.apply(this, {
items: [
{
xtype: 'fieldcontainer',
fieldLabel: 'P&L',
labelWidth: 100,
layout: 'hbox',
items: [{
xtype: 'textarea',
flex: 1
}]
}
]
});
this.callParent(arguments);
}});
Here If you want to Display text file in UI then what I will suggest you is put you text content in to JSON format and then on top of window or Panel you can display that.
In This example I am displaying on window. You can make as per your requirment.
Here is MyMessage function which can take the response and then display on MyMessageWindow .
MyMessage : function(){
var me = this;
Ext.Ajax.request({
url : URL of your JSON
method : 'GET',
dataType:'json',
scope : me,
headers : {
"Accept" : "application/json; charset=utf-8"
},
success : function (response, args) {
var data = Ext.decode(response.responseText);
var Msgtext = data.R.MSG; // This is depend on how you binding data in JSON.
me.MyMessageWindow(Msgtext);
}
});
},
MyMessageWindow : function(Msgtext){
var FailedMsgShow = function (text) {
Ext.create({
xtype: 'window',
title: 'P&L',
width: 600,
height: 450,
html:text,
scrollable: true,
}).show();
};
FailedMsgShow('<text style="color:green;">'+Msgtext+'</text>');
},
Note : You can display on any component like panel. I just suggesting you to put on window. you can make on panel as well instead of fieldContainer.

Adding dynamic items to the extjs panel which has layout accordion

Here I create simple extjs code which generates the accordion items dynamically. I used Panel + Layout (accordion).
I posted here because, It may help someone in future. I gone through so many test cases for this and even I searched on google but I could't find my things so I read extjs API and then I wrote out this.
My code:
Ext.onReady(function() {
var mtButton = Ext.create('Ext.button.Button',{
text : 'Add child',
handler : function() {
var numItems = myPanel.items.getCount() + 1;
myPanel.add({
title : 'Child number ' + numItems,
height : 60,
frame : true,
collapsible : true,
collapsed : true,
html : 'asdf'
});
myPanel.doLayout();
}
});
var addAccordion = function(panel){
for (var i = 1; i <= 3; i++) {
console.log(i);
panel.add({
title : 'Child number ' + i,
height : 60,
frame : true,
collapsible : true,
collapsed : true,
html : 'Demo for ' + i
});
}
};
var myPanel = Ext.create('Ext.panel.Panel', {
title: 'Accordion Layout',
width: 300,
height: 300,
renderTo: Ext.getBody(),
defaults: {
// applied to each contained panel
bodyStyle: 'padding:15px'
},
layout: {
// layout-specific configs go here
type: 'accordion',
titleCollapse: false,
animate: true,
activeOnTop: true
},
items : [],
tbar : [mtButton],
listeners: {
afterrender:addAccordion
}
});
});
I have very little knowledge of extjs. so, my question : is this the right way to do it? Or there is another way around?
What if I want items from json file? Is is possible? How?
Thanks in advance!
You can easily parse a json string to create components. Try something like this:
var jsonButton = Ext.create('Ext.button.Button', {
text: 'Add child from Json',
handler: function() {
var jsonString = {"xtype":"panel", "title":"Json Panel","height":50, "width":30};//valid json
myPanel.add({
xtype: jsonString.xtype,
title:jsonString.title,
height: jsonString.height,
width: jsonString.width,
});
myPanel.doLayout();
}
});
This will of course always create the same panel, but i think it can get you started.
Hope it helps :)
I figured out how to get items for panel which has layout specified. I am putting my code here.
My code is:
Ext.onReady(function() {
Ext.define('UserInfo', {
extend: 'Ext.data.Model',
fields: ['firstname', 'lastname', 'seniority' ]
});
var preStore = Ext.create('Ext.data.Store', {
storeId: 'addStore',
model: 'UserInfo',
autoLoad: 'true',
proxy: {
type: 'ajax',
url: 'example.json',
reader: {
type: 'json',
root: 'blah'
}
}
});
var addAccordion =
function(panel){
preStore.on('load', function () {
preStore.data.each(function(store) {
console.log(store.data['firstname']);
var firstname = store.data['firstname'];
var lastname = store.data['lastname'];
var seniority = store.data['seniority'];
panel.add({
title : firstname+' '+lastname,
html : seniority,
align : 'right',
});
});
});
};
var myPanel = Ext.create('Ext.panel.Panel', {
renderTo: Ext.getBody(),
defaults: {
// applied to each contained panel
bodyStyle: 'padding:50px',
width:120,
},
layout: {
// layout-specific configs go here
type: 'auto',
},
items : [],
//tbar : [mtButton],
listeners: {
afterrender:addAccordion
}
});
});
Is this the right way to do it?
Thank you in advance.

Fully update pie chart using ExtJS 4.2.0 and external datasource

I am currently creating a "drill-down" style pie chart, where clicking on a "slice" should update the pie chart with data within that slice.
Imagine for example an E-commerce report which shows sales by top level categories:
Shirts - $10,000
Pants - $8,000
Shoes - $3,500
Then clicking on the "Shirts" slice would display detailed information about sales in the Shirts category:
T-Shirts - $7,000
Polo Shirts - $2,000
Tank Tops - $1,000
I have a basic example here using a data source that returns random information:
http://jsfiddle.net/informationarchitech/BrMeh/
Ext.onReady(function () {
var level = 1;
Ext.define('Report', {
extend: 'Ext.data.Model',
fields: [{
name: 'category',
type: 'string'
}, {
name: 'purchases',
type: 'string'
}],
});
var store = Ext.create('Ext.data.Store', {
id: 'store',
model: 'Report',
autoLoad: true,
proxy: {
type: 'jsonp',
url: 'http://informationarchitech.com/demos/rand.php',
reader: {
root: 'content',
}
}
});
Ext.create('Ext.chart.Chart', {
renderTo: Ext.getBody(),
width: 500,
height: 350,
animate: true,
store: store,
series: [{
listeners: {
itemmousedown: function (obj) {
level++;
store.getProxy().url = 'http://informationarchitech.com/demos/rand.php?parent=' + obj.storeItem.data['category'] + '&level=' + level;
store.load();
}
},
type: 'pie',
angleField: 'purchases',
showInLegend: true,
label: {
field: 'category',
display: 'rotate',
contrast: true,
font: '18px Arial'
}
}]
});
});
As you can see, clicking on a slice results in inconsistent behavior. Sometimes it seems to update correctly, but often it seems to somehow be merging or overwriting the previous data.
I have tried every "clear," "update," "reset" method I can find, on the chart, the store, etc, and nothing I have tried seems to successfully "fully" update the pie chart with the new data. Can anyone tell me what I am doing wrong?

Looping Json array in Rowexpander plugin

I have a grid which I would like to show extra information with RowExpander plugin. When user click the cross, the json array should available in extended row. I tried everything but didn't successed to show the expanded content.
When I click the cross, I can see json array in console which is working well. But, the array content does not available in template.
Could you please help me, what I am doing wrong?
JSON ARRAY ( normal grid data )
[{"FORM_ID":"1","SUPPLIER_NO":"678456","SUPPLIER_NAME":"PINAR UNLU MAMÜLLER","RECORD_DATE":"12.06.2012","DELIVERY_NO":"215554","GRAND_TOTAL":"573","DRIVER_NAME":"Oğuz Çelikdemir","LICENSE_PLATE":"34 OGZ 6520"},{"FORM_ID":"2","SUPPLIER_NO":"75655463","SUPPLIER_NAME":"PINAR ET VE ET ÜRÜNLERİ","RECORD_DATE":"15.06.2012","DELIVERY_NO":"215556","GRAND_TOTAL":"619","DRIVER_NAME":"Murat Kayın","LICENSE_PLATE":"34 NES 7896"},{"FORM_ID":"3","SUPPLIER_NO":"32645668","SUPPLIER_NAME":"ÜLKER BİSKÜVİ","RECORD_DATE":"19.06.2012","DELIVERY_NO":"4563657","GRAND_TOTAL":"657","DRIVER_NAME":"Metin Yılmaz","LICENSE_PLATE":"06 ANK 6500"}]
JSON ARRAY ( expanded content )
[{"PRODUCT_NAME":"İÇECEK","QUANTITY":"2.00","SAS":"100","UNIT_ID":"1","UNIT_PRICE":"34.92","TOTAL":"70"},{"PRODUCT_NAME":"ŞARKÜTERİ","QUANTITY":"4.00","SAS":"100","UNIT_ID":"1","UNIT_PRICE":"34.92","TOTAL":"140"},{"PRODUCT_NAME":"KURU GIDA","QUANTITY":"1.00","SAS":"250","UNIT_ID":"1","UNIT_PRICE":"34.92","TOTAL":"35"},{"PRODUCT_NAME":"DETERJAN","QUANTITY":"5.00","SAS":"100","UNIT_ID":"1","UNIT_PRICE":"34.92","TOTAL":"175"},{"PRODUCT_NAME":"MEYVE SEBZE ve ET","QUANTITY":"3.00","SAS":"250","UNIT_ID":"1","UNIT_PRICE":"34.92","TOTAL":"105"}]
EXTJS
var formStore = new Ext.data.JsonStore({
url: 'form-data.php',
root: 'fdata',
idProperty: 'FORM_ID',
remoteSort: true,
fields: ['FORM_ID', 'SUPPLIER_NO', 'SUPPLIER_NAME', 'RECORD_DATE', 'DELIVERY_NO', 'DRIVER_NAME', 'LICENSE_PLATE',
{ name: 'GRAND_TOTAL', type: 'float'}]
});
formStore.setDefaultSort('RECORD_DATE', 'asc');
var checkboxSel = new Ext.grid.CheckboxSelectionModel();
var rowExpander = new Ext.grid.RowExpander({});
rowExpander.on('beforeexpand', function(rowexpander, record, body, rowindex) {
Ext.Ajax.request({
url: 'form-details.php' + '?fid=' + record.get('FORM_ID'),
method: 'GET',
success: function ( result, request ) {
var jsonData = Ext.util.JSON.decode(result.responseText);
tpl.overwrite(body, jsonData);
},
failure: function ( result, request ) {
Ext.MessageBox.alert('Failed', result.responseText);
return false;
}
});
return true;
});
var tpl = new Ext.Template(
'<p>URUN ADI : {PRODUCT_NAME}</p><br/>',
'<p>TOPLAM : {QUANTITY}</p>'
);
Ext.onReady(function() {
var grid = new Ext.grid.GridPanel({
title: 'ME.117.10 - Hammaliye Formu',
store: formStore,
sm: checkboxSel,
columns: [
checkboxSel, rowExpander,
{ header: "ID",
width: 40,
dataIndex: 'FORM_ID',
sortable: false
},
{ header: "Satıcı No",
id: 'form-id',
dataIndex: 'SUPPLIER_NO',
width: 40,
sortable: false
},
{ header: "Satıcı Firma",
dataIndex: 'SUPPLIER_NAME',
width: 290,
sortable: true
},
{ header: "Kayıt Tarihi",
width: 80,
dataIndex: 'RECORD_DATE',
sortable: true
},
{ header: "İrsaliye No",
width: 80,
dataIndex: 'DELIVERY_NO',
sortable: false
},
{ header: "Tutar",
width: 80,
dataIndex: 'GRAND_TOTAL',
sortable: false
}
],
autoExpandColumn: 'form-id',
renderTo: document.getElementById('form-results'),
width: 750,
height: 500,
loadMask: true,
columnLines: true,
plugins: rowExpander
});
formStore.load();
});
I assume you're using ExtJS 3.x as that's what your coding reflects. If you need help doing it in ExtJS 3.x I cannot help you much, I'm more used to the ExtJS 4.x way of coding, so that's what I'll use to try to explain this.
I am working to implement a nested grid just like this and have just been through this procedure:
Basically you need to config your main grid with a rowexpander plugin, which you have already done (below is the way I did it):
plugins: [{
ptype: "rowexpander",
rowBodyTpl: ['<div id="SessionInstructionGridRow-{ClientSessionId}" ></div>']
}],
Then in your controller you will just have to set up an event to happen on expandbody which is a rowexpander event:
this.control({
'gridview' : {
expandbody : this.onGridExpandBody
}
});
And then finally you write your script to the <div> tag you created in rowexpander plugin template:
onGridExpandBody : function(rowNode, record, expandbody) {
var targetId = 'SessionInstructionGridRow-' + record.get('ClientSessionId');
if (Ext.getCmp(targetId + "_grid") == null) {
var sessionInstructionGrid = Ext.create('TS.view.client.SessionInstruction', {
renderTo: targetId,
id: targetId + "_grid"
});
rowNode.grid = sessionInstructionGrid;
sessionInstructionGrid.getEl().swallowEvent(['mouseover', 'mousedown', 'click', 'dblclick', 'onRowFocus']);
sessionInstructionGrid.fireEvent("bind", sessionInstructionGrid, { ClientSessionId: record.get('ClientSessionId') });
}
}
Read: Nested grid with extjs 4 for more info.

extjs grid: re-get data from server when click button

I am try to research Extjs- grid. I created a button to display grid when click it. My code like below:
function onDisplay() {
Ext.onReady(function () {
var proxy = new Ext.data.HttpProxy({
url: 'server.jsp'
});
var reader = new Ext.data.JsonReader({}, [{
name: 'bookId',
mapping: 'bookId'
}, {
name: 'bookName'
}])
var gridStore = new Ext.data.Store({
proxy: proxy,
reader: reader
});
gridStore.load();
cols = [{
header: "bookId",
width: 60,
dataIndex: 'bookId',
sortable: true
}, {
header: "bookName",
width: 60,
dataIndex: 'bookName',
sortable: true
}];
var firstGrid = new Ext.grid.GridPanel({
store: gridStore,
columns: cols,
renderTo: 'example-grid',
width: 540,
height: 200
});
});
}
But when i click button N times -> it is displayed N grids. I only want display one grid and after click button it will get data from server again.
Please help me.
Thank you
You might want to look at some of the ExtJS Grid examples. They have lots of information about rendering grids from a store, and creating toolbars (which may include refresh buttons, for example). After cleaning up your example code a bit, I've come up with this:
Ext.onReady(function(){
var proxy=new Ext.data.HttpProxy( {url:'server.jsp'});
var reader=new Ext.data.JsonReader({},[
{name: 'bookId', mapping: 'bookId'},
{name: 'bookName'}
])
var gridStore=new Ext.data.Store({
proxy:proxy,
reader:reader
autoLoad:true
});
cols= [
{header: "bookId", width: 60, dataIndex: 'bookId', sortable: true},
{header: "bookName", width: 60, dataIndex: 'bookName', sortable: true}
];
var firstGrid = new Ext.grid.GridPanel({
store : gridStore,
columns : cols,
renderTo :'example-grid',
width :540,
height :200
});
//this code should ensure that only the grid updates,
//rather than rendering a whole new grid each time
var button = Ext.Button({
renderTo: "ButtonContainerId",
listeners: {
'click': function() {
gridStore.load()
}
}
})
});

Resources