Extjs MVC run function after store loads - json

I've got a grid getting data through a json store. I want to display the total number of rows in the grid. The problem is that the store.count() function is running before the store loads so it is returning 0. How can I get my count function to run only once the store has loaded? I'm working in MVC, here is my app.js which has my counting logic in it.
Thank you for any help
Ext.application({
name: 'AM',
appFolder: 'app',
controllers: [
'Users'
],
launch: function(){
Ext.state.Manager.setProvider(Ext.create('Ext.state.CookieProvider'));
Ext.create('Ext.container.Viewport', {
resizable: 'true',
forceFit: 'true',
layout: 'fit',
items:[{
xtype: 'userpanel',
}]
});
var port = Ext.ComponentQuery.query('viewport')[0],
panel = port.down('userpanel'),
grid = panel.down('userlist'),
label = panel.down('label');
var count = grid.store.getCount();
var labelText = "Number of people in list: " + count;
label.setText(labelText);
}
});
store code:
Ext.define('AM.store.Users', {
extend: 'Ext.data.Store',
model: 'AM.model.User',
autoLoad: true,
autoSync: true,
purgePageCount: 0,
proxy: {
type: 'rest',
url: 'json.php',
reader: {
type: 'json',
root: 'queue',
successProperty: 'success'
}
},
sortOnLoad: true,
//autoLoad: true,
sorters: [
{
property: 'PreReq',
direction: 'DESC'
},
{
property: 'Major1',
direction: 'ASC'
},
{
property: 'UnitsCompleted',
direction: 'DESC'
}
],
listeners:{
onload: function(){
var port = button.up('viewport'),
grid = port.down('userlist'),
panel = port.down('userpanel'),
label = panel.down('label'),
count = grid.store.getCount(),
labelText = "Number of people in list: " + count;
label.setText(labelText);
},
scope: this
}
});
grid code:
Ext.define('AM.view.user.List' , {
extend: 'Ext.grid.Panel',
alias: 'widget.userlist',
store: 'Users',
height: 'auto',
width: 'auto',
//resizable: 'true',
features:[{
ftype: 'grouping'
}],
autoFill: 'true',
layout: 'fit',
autoScroll: 'true',
initComponent: function() {
function renderTip(value, metaData, record, rowIdx, colIdx, store) {
metaData.tdAttr = 'data-qtip="' + value + '"';
return value;
};
var dateRender = Ext.util.Format.dateRenderer('m/d/Y');
this.columns=[
//code for all my columns
]
];
this.callParent(arguments);
}
});

Try putting a listener on the store then listen for the onload event get the count and update the field that way. Though there are many ways to do this that is just one.
But in the example above you never load the store you just create it, which is why you see zero.

figured it out, needed to add a listener for the "load" event, not "onLoad". Code below...
Ext.define('APP.store.Store', {
extend: 'Ext.data.Store',
model: 'APP.model.Model',
autoLoad: true,
autoSync: true,
purgePageCount: 0,
proxy: {
type: 'rest',
url: 'json.php',
reader: {
type: 'json',
root: 'users',
successProperty: 'success'
}
},
sortOnLoad:true,
sorters: [{
property: 'last',
direction: 'ASC'
}],
listeners: {
load:{
fn:function(){
var label = Ext.ComponentQuery.query('#countlabel')[0];
label.setText(this.count()+ ' Total Participants);
}
}
}
});

Related

Extjs create form items with json store

I have created a form panel view and I will create some form items iside this panel. The communication to the store, controller and model works fine but how can I create the items in the view?
Json array (retrieved from external service):
{
"data": [
{
"name": "ff",
"xtype": "textfield",
"allowBlank": false,
"fieldLabel": "labelText1"
},
{
"name": "fsdsdf",
"xtype": "textfield",
"allowBlank": false,
"fieldLabel": "labelText2"
}
],
"msg": "Unknown",
"success": true
}
Store:
Ext.define('myApp.store.Forms', {
extend: 'Ext.data.Store',
alias: 'store.Form',
model: 'myApp.view.FormModel',
constructor: function(config) {
var me = this;
config = config || {};
me.callParent([Ext.apply({
autoLoad: true,
proxy: {
type: 'ajax',
url: 'url_to_service',
reader: {
type: 'json',
rootProperty: 'data',
successProperty : 'success'
}
},
storeId: 'formStore'
}, config)]);
// console.error("store loaded");
// console.info(me);
}
});
model
Ext.define('myApp.view.FormModel', {
extend: 'Ext.data.Model',
data: {
name: 'myApp'
}
});
Controller
Ext.define('myApp.view.FormController', {
extend: 'Ext.app.ViewController',
alias: 'controller.form',
init: function(application) {
var store = new myApp.store.Forms();
store.on("metachange", metaChanged, this);
function metaChanged(store, meta) {
var grid = Ext.ComponentQuery.query('form')[0];
grid.fireEvent('metaChanged', store, meta);
};
this.control({
"form": {
metaChanged: this.handleStoreMetaChange
}
});
},
handleStoreMetaChange: function(store, meta) {
var form = Ext.ComponentQuery.query('form')[0];
form.reconfigure(store, meta.data);
}
});
At least the view where I want to create the items from the store.
Ext.define('myApp.view.Form', {
extend: 'Ext.form.Panel',
xtype: 'form',
controller: "form",
viewModel: {
type: "form"
},
title: 'form',
bodyPadding: 10,
autoScroll: true,
defaults: {
anchor: '100%',
labelWidth: 100
},
// How can I add form items here?
});
Within your view you'll need to create a function that matches the form.reconfigure(store, meta.data) call you are making in your controller.
And in that function you can call the form's add function to add items to the form. As you are already supplying the xtype and configuration parameters in the data structure each item can be passed to the add function as it. It would look something like the below code...
reconfigure: function(store, data) {
var me = this;
Ext.each(data, function(item, index) {
me.add(item);
});
}
I have knocked together an Example Fiddle that shows this working. I just mocked out the loading of the data and 'metachange' event as it was easier to get the demo working.

Retrieving nested JSON data - Ext JS

Let's start off with my store:
var newstore = Ext.create('Ext.data.Store', {
fields: ['id', 'table_name', 'name', 'description']
proxy: {
type: 'memory'
}
});
I have some example data here, which comes from a dynamic json response:
{
"elements":[
{
"element":{
"name":"Element Name", <---- This is the value I need**
"id":"Element ID",
"attributes":[
{
"attrname":"id",
"attrvalue":"This is the ID"
},
{
"attrname":"name",
"attrvalue":"This is the name"
},
{
"attrname":"description",
"attrvalue":"This is the description"
},
{
"attrname":"table_name",
"attrvalue":"This is the table"
}
]
}
}
}
And I decode my json here, which places it neatly into my store:
for( var i=0; i < decoded.elements.length; i++ ) {
var element = decoded.elements[ i ].element;
var element_name = element.name; <---- THIS retrieves that value I need
var model = {};
// loop over attributes
for( var x=0; x < element.attributes.length; x++ ) {
var attribute = element.attributes[ x ];
model[ attribute.attrname ] = attribute.attrvalue;
}
// implicitly cast data as Model
newstore.add( model );
}
And lastly, my grid - ResponseList.js:
var grid = Ext.define('MyApp.view.ResponseList' ,{
initComponent: function(columns) {
//config
this.columns = [
{header: 'Element Name', dataIndex: 'What goes here ???'},
{header: 'ID', dataIndex: 'id'},
{header: 'View Name', dataIndex: 'name'},
{header: 'Description', dataIndex: 'description'},
{header: 'Table Name', dataIndex: 'table_name'},
etc...
My question is, how do I place that first name value, Element Name into the first row of my grid? The name name is already taken for the attributes.attrname field, so I'm not sure how to proceed. Everything except Element Name displays just fine.
[Edit]: This is how I want my grid to look:
Any help is appreciated thanks!
In your fields in the store or in a model you can specify mapping which allows for nested json data:
var model = Ext.define('myModel', {
extend: 'Ext.data.Model',
fields: [{
name: 'id',
mapping: 'element.id',
type: 'auto'
}],
proxy: {
type: 'ajax',
url: 'data.json',
reader: {
type: 'json',
root: 'elements',
successProperty: ''
}
}
});
var store = Ext.create('Ext.data.Store', {
model: model,
autoLoad: true,
listeners: {
load: function() {
console.log(store);
}
}
});
var grid = Ext.create('Ext.grid.Panel', {
renderTo:Ext.getBody(),
store:store,
columns: {
defaults: {},
items: [{
header: "Id",
dataIndex: "id",
hidden: false
}]
}
});
Here is a fiddle demonstrating working code.
You can probably use the renderer on the grid to get the value you actually need.
{header: 'Element Name', dataIndex: 'What goes here ???',
renderer: function(value, metaData, record, row, col, store, gridView){
return record.someAttribute;
}
},
I'm not sure of the structure of your record, but I think you can guess how to go on from here.
Also, I don't think all that manual decoding is necessary, I can't figure out how you want your grid to look, but if you post a sketch of it or something maybe we can make all that decoding look cleaner.

URL field not working with flexigrid no response from URL

When I pass the URL I am getting a no response from the url otherwise if I specify the corresponding WCF service page which is included in my project it is working is it any cross domain issue what would be the possible issue
<form id="sform" runat="server">
<table id="flex2" style="display:none"></table>
<script type="text/javascript">
$(document).ready(function () {
var user_id = 1;
var data = { UserID: user_id };
$("#flex2").flexigrid({
useInlineEditor: true,
//singleSelect: true,
rowClick: function (row) {
//var r=this.DataSource.rows[row.rowIndex];
//var p=$(row).offset();
//alert(r[this.DataSource.key]+" "+r.Name+" offset:"+p.top+","+p.left);
//this.grid.inlineEditor.edit(row);
},
url: 'http://192.168.10.91:5001/Service.svc/GetStates',
method: 'POST',
dataType: 'json',
colModel: [
{ display: 'Hours', name: 'hours', width: 40, sortable: true, align: 'center' },
{ display: 'DOC', name: 'doc', width: 180, sortable: true, align: 'left' },
],
searchitems: [
{ display: 'Type', name: 'cmetype' }
],
onError: function (jqXHR, textStatus, errorThrown) {
alert("flexigrid failed " + errorThrown + jqXHR + textStatus);
},
sortname: "type",
sortorder: "asc",
usepager: true,
title: 'States',
useRp: true,
rp: 15,
showTableToggleBtn: true,
width: 800,
height: 200
});
});
//This function adds paramaters to the post of flexigrid. You can add a verification as well by return to false if you don't want flexigrid to submit
function addFormData() {
//passing a form object to serializeArray will get the valid data from all the objects, but, if the you pass a non-form object, you have to specify the input elements that the data will come from
var dt = $('#sform').serializeArray();
$("#flex2").flexOptions({ params: dt });
return true;
}
$('#sform').submit(function () {
$('#flex2').flexOptions({ newp: 1 }).flexReload();
return false;
});
</script>
</form>
Make sure that the svc service is accesibile and that it can accept post requests.
If all works well, check that the response is JSON and is valid.

ExtJS-Parsing json data and display in view

I am calling a rest webscript using Extjs with JSON,but unable to display on view.
The problem is i am getting the json data as response from the server.But when i want to display on view.Its not getting displayed.
here is my json:
{
"data":
{
"ticket":"TICKET_87c91dd9d18d7242e44ff638df01e0cb388ee4c7"
}
}
and here is extjs code:
Ext.onReady(function() {
alert("in login js");
var store = new Ext.data.JsonStore({
proxy : new Ext.data.ScriptTagProxy({
// url : 'http://ip:8080/alfresco/service/api/login',
url : 'http://ip:8080/alfresco/service/api/login?u=Value1&pw=Value2&format=json',
method : 'GET'
}),
reader : new Ext.data.JsonReader({
root : 'data',
fields : ['ticket']
})
});
alert("after the webscript call");
//store.load();
var grid = new Ext.grid.GridPanel({
renderTo: 'PagingFragment',
frame:true,
width:600,
height:800,
autoHeight: true,
autoWidth: true,
store: store,
loadMask:true,
columns: [
{
height:100,
width:100,
header: "Ticket",
dataIndex: 'ticket',
// renderer: title_img,
//id: 'ticket',
sortable: true
}
],
bbar: new Ext.PagingToolbar({
pageSize: 2,
store:store,
displayInfo: true,
displayMsg: 'Displaying topics {0} - {1} of {2}'
}),
sm: new Ext.grid.RowSelectionModel({
singleSelect: true,
listeners: {
rowselect: {
fn: function(sm,index,record) {
Ext.Msg.alert('You Selected',record.data.title);
}
}
}
})
});
store.load({
params: {
start: 0,
limit: 5
}
});
});
and in jsp:
<body>
<div id="PagingFragment" style="position:absolute;top:10px;left:200px">
</div>
</body>
could anybody help on this
'data' must be an array.
Instead of { data: { ticket: 'blahblahblah' } } you must return
{ data: [{ ticket: 'blahblahblah' }] } see the diference?

how to update or refresh the content of tab panel in sencha touch

i have list of items, while click the particular list item it will show the details of that item.. i have problem, for the first item click it shows the correct result but while click the next item i am getting that particular item details but it showing the old item details.this is my code
RadMobApp.views.patPanel = Ext.extend(Ext.Panel, {
id: 'pathView',
layout : 'fit',
initComponent: function() {
this.titleTxtc = new Ext.Component({
cls : 'top_title_text',
html: 'History'
});
this.backButton = new Ext.Button({
text: 'back',
height:15,
ui:'back',
handler: function () {
controller.showPanel();
},
scope: this
});
this.titleBar = new Ext.Toolbar({
dock: 'top',
cls: "top_tool_bar2",
height: 42,
items: [this.backButton, {xtype: 'spacer'}, this.titleTxtc, {xtype: 'spacer'}]
});
var tabs = new Ext.TabPanel({
xtype:"tabpanel",
id: 'tabpanel',
renderTo: Ext.getBody(),
width:400,
height: 150,
activeTab: 0,
layoutOnTabChange: true,
tabBar: {
cls: "top_tab_panel1",
height: 42,
style: 'padding-left:2px;'
},
items: [{
xtype: 'Panel1',
id: 'panel1',
title: 'Panel1',
height: 100
},{
xtype: 'Panel2',
id: 'panel2',
title: 'Panel2',
height: 100
},{
xtype: 'panel3',
id: 'panel3',
title: 'Panel3',
height: 100,
listeners: {
beforeshow: function(p) {
scope: this;
/* var tabPanel = p.ownerCt;
var tabEl = tabPanel.getTabEl(prmPanel);
Ext.fly(tabEl).child('span.x-tab-strip-text',
true).qtip = 'Tab is now enabled';
Ext.getCmp('panel2').enable(); */
}
}
}]
});
this.dockedItems = [this.titleBar];
this.items = [tabs];
RadMobApp.views.patPanel.superclass.initComponent.call(this);
}
});
how to clear the tab panel? Thanks in advance
try putting the config option
remoteFilter : true
to your store from which you are loading the data to the list.ie
new Ext.data.Store({
model: 'Test',
sortOnLoad: true,
remoteFilter : true,
autoLoad: true,
getGroupString : function(record) {
return record.get('FullName_FirstLast')[0];
},
proxy: {
type: 'ajax',
url : testUrl,
reader: {
type: 'json',
root: 'test'
}
}
})