How to refresh / reload Grid - javascript

hi this is my code i am trying to refresh grid panel on clicking refresh button in toolbar , but it wont work anymore or nothing happens can you please help me what is the proper syntax ?
var store = new Ext.data.JsonStore({
url: 'data-cloud.php',
fields: [{
name: 'userid'
}, {
name: 'record_name'
}, {
name: 'search_term',
type: 'string'
}]
});
var grid_array = new Array();
store.load({
params: {
start: 0,
limit: 5
}
});
store.on('load', function(store, records) {
for (var j = 0; j < records.length; j++) {
grid_array[j] = records[j].get('record_name');
}
});
// create the Grid
var datagrid = new Ext.grid.GridPanel({
store: store,
columns: [{
id: 'id',
header: 'Cloud Name',
width: 155,
renderer: record_name,
sortable: true,
dataIndex: 'record_name'
}, {
header: 'Search Term',
width: 150,
sortable: true,
dataIndex: 'search_term'
}],
stripeRows: true,
height: 250,
width: 500,
id: 'cloud_panel',
title: 'DB Grid',
id: 'detailPanel',
tbar: [{
text: 'Refresh',
iconCls: 'new-topic',
handler: function() {
Ext.getCmp('detailPanel').getView().refresh();
}
}
],
bbar: new Ext.PagingToolbar({
pageSize: 5,
store: store,
displayInfo: true,
displayMsg: 'Displaying topics {0} - {1} of {2}',
emptyMsg: "No topics to display"
})
});

var grid = Ext.getCmp('cloud_panel');
...
tbar: [
handler: function() {
grid.load();
}
]

If you refresh the grid's view, the data will not be loaded again, it will just re-render the presentation.
To refresh the actual data, use the reload function on the grid's store:
Ext.getCmp('detailPanel').getStore().reload();
Btw, you're setting the id property twice in your grid's configuration, "cloud_panel" and "detailPanel", so you'll probably want to eliminate one of them.

try
var grid = Ext.getCmp('cloud_panel');
grid.getStore().load();
also you can pass params to store
grid.getStore().getProxy().extraParams = {name:'name1', lname: 'lname'}
and after
grid.getStore().load(function(){
alert('store was loaded');
});

Related

Ext JS grid sort sent as a String instead of JSON

I am trying to implement server-side sorting with Sencha Ext JS and noticed something odd. The paging portion of the JSON looks fine but the sort property is set as a String and not an Array:
Actual:
{"page":1,"start":0,"limit":50,"sort":"[{\"property\":\"firstName\",\"direction\":\"ASC\"}]"}
Expected:
{"page":1,"start":0,"limit":50,"sort":[{"property":"firstName","direction":"ASC"}]}
ExtJs Code:
Ext.require([
'Ext.grid.*',
'Ext.data.*',
'Ext.panel.*',
'Ext.layout.container.Border'
]);
Ext.define('Customer',{
extend: 'Ext.data.Model',
fields: [
{name: 'id', type: 'int'},
{name: 'firstName', type: 'string'},
{name: 'lastName', type: 'string'},
{name: 'companyName', type: 'string'}
]
});
Ext.onReady(function(){
var itemsPerPage = 50; // Paging
var store = Ext.create('Ext.data.Store', {
pageSize: itemsPerPage,
// autoLoad: true,
autoLoad: {start: 0, limit: itemsPerPage},
autoSync: true,
model: 'Customer',
remoteSort: true,
proxy: {
paramsAsJson: true,
actionMethods: {
read: 'POST'
},
type: 'rest', // was... 'ajax',
url: '/customers',
reader: {
type: 'json',
root: 'content',
totalProperty: 'totalElements'
},
writer: {
type: 'json'
},
listeners: {
write: function(store, operation){
var record = operation.getRecords()[0],
name = Ext.String.capitalize(operation.action),
verb;
if (name == 'Destroy') {
record = operation.records[0];
verb = 'Destroyed';
} else {
verb = name + 'd';
}
Ext.example.msg(name, Ext.String.format("{0} user: {1}", verb, record.getId()));
}
}
}
});
var rowEditing = Ext.create('Ext.grid.plugin.RowEditing', {
listeners: {
cancelEdit: function(rowEditing, context) {
// Canceling editing of a locally added, unsaved record: remove it
if (context.record.phantom) {
store.remove(context.record);
}
}
}
});
// create the grid
var grid = Ext.create('Ext.grid.Panel', {
bufferedRenderer: false,
store: store,
columns: [
{text: "ID", width: 120, dataIndex: 'id', sortable: true},
{text: "First Name", flex: 1, dataIndex: 'firstName', sortable: true, editor: 'textfield'},
{text: "Last Name", width: 125, dataIndex: 'lastName', sortable: true, editor: 'textfield'},
{text: "Company Name", width: 125, dataIndex: 'companyName', sortable: true}
],
forceFit: true,
height:210,
split: true,
region: 'north',
plugins: [rowEditing],
// Paging
dockedItems: [{
xtype: 'pagingtoolbar',
store: store, // same store GridPanel is using
dock: 'bottom',
displayInfo: true
}],
});
// define a template to use for the detail view
var customerTplMarkup = [
'ID: {id}<br/>',
'First Name: {firstName}<br/>',
'Last Name: {lastName}<br/>',
'Company Name: {companyName}<br/>'
];
var customerTpl = Ext.create('Ext.Template', customerTplMarkup);
Ext.create('Ext.Panel', {
renderTo: 'binding-example',
frame: true,
title: 'Customer List',
width: 580,
height: 400,
layout: 'border',
items: [
grid, {
id: 'detailPanel',
region: 'center',
bodyPadding: 7,
bodyStyle: "background: #ffffff;",
html: 'Please select a customer to see additional details.'
}]
});
// update panel body on selection change
grid.getSelectionModel().on('selectionchange', function(sm, selectedRecord) {
if (selectedRecord.length) {
var detailPanel = Ext.getCmp('detailPanel');
detailPanel.update(customerTpl.apply(selectedRecord[0].data));
}
});
});
i added beforeload listener to the store
here is a working example:
listeners: {
beforeload: function(store, operation, eOpts){
var sort = [];
var filter = [];
if(operation._sorters){
for(var i = 0; i< operation._sorters.length; i++){
var direction = operation._sorters[i]._direction;
var property = operation._sorters[i]._property;
sort.push({
"direction" : direction,
"property" : property
});
}
operation._proxy.extraParams = {sort:sort};
}
if(operation._filters){
for(var i = 0; i< operation._filters.length; i++){
var operator = operation._filters[i]._operator;
var property = operation._filters[i]._property;
var value = operation._filters[i]._value;
filter.push({
"operator" : operator,
"property" : property,
"value" : value
});
}
operation._proxy.extraParams = {filter:filter};
}
}
}

Trying to pop-up window that contains a form, but form not shown - extjs 5

I am trying to display a pop-up window that contains a form in extjs 5, using django-rest as backend. I manage to get the pop-up window shown, but the form inside it is not shown. If I put just an html tag instead of the form, the tag contents are shown. I am very confused as I can't make it work to show the form. Any help would be so much appreciated. The codes are:
Controller:
Ext.define('MyApp.controller.Manage', {
extend: 'Ext.app.Controller',
views: ['Manage'],
// controller initialisation
init: function() {
// save scope
var manageController = this;
console.log('manage controller started');
// instanciate view class but hide initially
this.view = this.getView('Manage').create().hide();
// Request manage variables (lastDayUpd)
Ext.Ajax.request({
url: '/api/manage/',
method: 'GET',
success: function(response, options){
console.log('got last day upd');
// Decode response
var res = Ext.util.JSON.decode(response.responseText).results[0].lastDayUpd;
console.log(res);
// Get manage panel from container
var cp = (Ext.ComponentQuery.query('container#manageContentPanel')[0]).getComponent('lastDayUpd');
// Set data to display last day updated
cp.setConfig('html', ('Last day updated: '+res));
},
failure: function(response, options) {
console.log('not got last day upd');
}
});
this.control({
// register for the logout-click
'#logoutButton': {
click: function() {
// mask the complete viewport
this.view.mask('Logout…')
// ask the login-controller to perform the logout in the backend
MyApp.getApplication().getController('Login').performLogout(function(success) {
if(!success) {
// return WITHOUT unmasking the main app, keeping the app unusable
return Ext.Msg.alert('Logout failed', 'Close and restart the Application')
}
// unmask and hide main viewport and all content
this.view.unmask();
this.view.hide();
// relaunch application
MyApp.getApplication().launch();
});
}
},
// register for click in the navigation tree
'#navTree': {
itemclick: function(tree, node) {
// ignore clicks on group nodes
// TODO: pass click on to first sub-item
// ignore clicks on non-leave nodes (groups)
if(!node.data.leaf)
return;
// pass the id of the clicked node to the content-panel
// enable the corresponding content view
this.getContentPanel().setActiveItem(node.data.itemId);
}
},
// Show update form to perform update
'#updButton': {
click: function(){
//alert('Clicked');
//navigationController.getController('Manage').view.show()
this.showUpdateForm();
}
}
});
},
showUpdateForm: function(){
// Get manage panel from container
var form = (Ext.ComponentQuery.query('container#manageContentPanel')[0]).getComponent('updateDaskalosBox').show();
console.log('form is:');
console.log(form);
console.log('show update form');;
},
});
View:
Ext.define('MyApp.view.Manage', {
layout: 'border',
extend: 'Ext.container.Container',
renderTo: Ext.getBody(),
id: "manageContainer",
// todo: not resizing correctly
width: '100%',
height: '100%',
items: [{
region: 'west',
xtype: 'treepanel',
itemId: 'navTree',
width: 150,
split: true,
rootVisible: false,
title: 'Navigation',
tbar: [
{ text: 'Logout', itemId: 'logoutButton' }
]
},
{
region: 'center',
xtype: 'container',
itemId: 'manageContentPanel',
layout: {
type: 'border',
//columns: 3,
//deferredRender: true
},
items: [
{
itemId: 'lastDayUpd',
title: 'Manage Daskalos',
xtype: 'panel',
buttons: [
{
text: 'Update',
itemId: 'updButton'
},
{
text: 'Back',
itemId: 'backButton',
}
],
html: 'Last Day Updated: '
},
{
xtype: 'messagebox',
itemId: 'updateDaskalosBox',
layout: 'fit',
title: 'Update daskalos',
//html: 'A pop up',
//floating: true,
//closable : true,
items: [
{
xtype: 'panel',
itemId: 'updateDaskalosPanel',
//layout: 'fit',
items: [
{
xtype: 'form',
itemId: 'updateDaskalosForm',
//url: '', // to fill
layout: 'fit',
//renderTo: 'updateForm',
fieldDefaults: {
labelAlign: 'left',
labelWidth: 100
},
buttons: [
{
text: 'Update',
itemId: 'updButton',
formBind: true,
},
{
text: 'Cancel',
itemId: 'cancelButton',
}
],
items: [
//Just one field for now to see if it works
//{
//xtype: 'datefield',
////anchor: '100%',
//fieldLabel: 'From',
////name: 'from_date',
////maxValue: new Date() // limited to the current date or prior
//},
{
fieldLabel: 'Last Name',
name: 'last',
allowBlank: false
}
],
},
],
},
],
},
]
}
],
});
After controller initialization, I want when the user clicks the update button to pop up a window that contains a form to post data to the server. The pop-up is thrown, but the form inside the panel that the window contains as child item seems that has the problem. Does anyone see what I miss here?
Thanks for the help! Babis.
Why you dont just create a window containing a form? Your "pop-up window" is a messagebox, that you abuse. There is also no need to put a form in a panel. A form extends from panel.
// you have some trailing commas in your code
Ext.define('MyApp.view.Manage', {
extend: 'Ext.window.Window',
alias : 'widget.manage',
requires: ['Ext.form.Panel'],
height: 300,
width: 600,
layout: 'fit',
resizable: false,
autoShow: true,
animCollapse:false,
iconCls: 'icon-grid',
initComponent: function() {
this.items = [{
xtype: 'form',
/*
*
* Start you code for form
*/
}];
this.callParent(arguments);
}
});
You want a form in a window, but can you tell why are you extending container ??

How to access plugin in ExtJs MVC

I am trying to add a toolbar to my grid with an "Add New Record" button.
The code example provided by Sencha is here:
var rowEditing = Ext.create('Ext.grid.plugin.RowEditing', {
clicksToMoveEditor: 1,
autoCancel: false
});
// create the grid and specify what field you want
// to use for the editor at each column.
var grid = Ext.create('Ext.grid.Panel', {
store: store,
tbar: [{
text: 'Add Employee',
iconCls: 'employee-add',
handler : function() {
rowEditing.cancelEdit();
// Create a model instance
var r = Ext.create('Employee', {
name: 'New Guy',
email: 'new#sencha-test.com',
start: new Date(),
salary: 50000,
active: true
});
store.insert(0, r);
rowEditing.startEdit(0, 0);
}
}],
//etc...
});
Example: http://dev.sencha.com/deploy/ext-4.1.0-gpl/examples/grid/row-editing.html
I am having trouble applying this to my code since I use the MVC pattern. This is my code:
Ext.define('RateManagement.view.Grids.AirShipmentGrid', {
extend: 'Ext.grid.Panel',
xtype: 'AirShipmentGrid',
plugins: [
{
clicksToMoveEditor: 1,
autoCancel: false,
ptype: 'rowediting'
},
'bufferedrenderer'
],
tbar: [{
text: 'Add Rate',
//iconCls: 'rate-add',
handler : function() {
rowEditing.cancelEdit(); // rowEditing is not defined...
// Create a model instance
var r = Ext.create('Employee', {
name: 'New Guy',
email: 'new#sencha-test.com',
start: new Date(),
salary: 50000,
active: true
});
store.insert(0, r);
rowEditing.startEdit(0, 0); // rowEditing is not defined...
}
}],
// etc...
});
How can I access the "rowEditing" plugin so as to call it's required methods?
the handler from the buttons gets a reference to the button as a first argument. You can use that reference with a componentquery to get a reference to your grid panel that houses it. The gridPanel has a getPlugin method with which you can fetch a plugin based on a pluginId.The only thing you have to make sure of is to give the plugin a pluginId, otherwise the Grid cannot find it. This should work:
Ext.define('RateManagement.view.Grids.AirShipmentGrid', {
extend: 'Ext.grid.Panel',
xtype: 'AirShipmentGrid',
plugins: [
{
clicksToMoveEditor: 1,
autoCancel: false,
ptype: 'rowediting',
pluginId: 'rowediting'
},
'bufferedrenderer'
],
tbar: [{
text: 'Add Rate',
//iconCls: 'rate-add',
handler : function(button) {
var grid = button.up('gridpanel');
var rowEditing = grid.getPlugin('rowediting');
rowEditing.cancelEdit(); // rowEditing is now defined... :)
// Create a model instance
var r = Ext.create('Employee', {
name: 'New Guy',
email: 'new#sencha-test.com',
start: new Date(),
salary: 50000,
active: true
});
store.insert(0, r);
rowEditing.startEdit(0, 0); // rowEditing is not defined...
}
}],
// etc...
});
Cheers, Rob
EDIT: added complete example:
- Go to http://docs.sencha.com/extjs/4.2.2/extjs-build/examples/grid/row-editing.html
- Open the javascript console
- Paste the below code in there
It will create a second grid with a button that finds the row editing plugin and cancels your edit. doubleclick a row to start editing, click the button in the tbar to cancel it. Works like a charm. Make sure you have specified the pluginId, otherwise the grid's getPlugin method cannot find it.
Ext.require([
'Ext.grid.*',
'Ext.data.*',
'Ext.util.*',
'Ext.state.*',
'Ext.form.*'
]);
Ext.onReady(function() {
// Define our data model
Ext.define('Employee', {
extend: 'Ext.data.Model',
fields: [
'name',
'email', {
name: 'start',
type: 'date',
dateFormat: 'n/j/Y'
}, {
name: 'salary',
type: 'float'
}, {
name: 'active',
type: 'bool'
}
]
});
// Generate mock employee data
var data = (function() {
var lasts = ['Jones', 'Smith', 'Lee', 'Wilson', 'Black', 'Williams', 'Lewis', 'Johnson', 'Foot', 'Little', 'Vee', 'Train', 'Hot', 'Mutt'],
firsts = ['Fred', 'Julie', 'Bill', 'Ted', 'Jack', 'John', 'Mark', 'Mike', 'Chris', 'Bob', 'Travis', 'Kelly', 'Sara'],
lastLen = lasts.length,
firstLen = firsts.length,
usedNames = {},
data = [],
s = new Date(2007, 0, 1),
eDate = Ext.Date,
now = new Date(),
getRandomInt = Ext.Number.randomInt,
generateName = function() {
var name = firsts[getRandomInt(0, firstLen - 1)] + ' ' + lasts[getRandomInt(0, lastLen - 1)];
if (usedNames[name]) {
return generateName();
}
usedNames[name] = true;
return name;
};
while (s.getTime() < now.getTime()) {
var ecount = getRandomInt(0, 3);
for (var i = 0; i < ecount; i++) {
var name = generateName();
data.push({
start: eDate.add(eDate.clearTime(s, true), eDate.DAY, getRandomInt(0, 27)),
name: name,
email: name.toLowerCase().replace(' ', '.') + '#sencha-test.com',
active: getRandomInt(0, 1),
salary: Math.floor(getRandomInt(35000, 85000) / 1000) * 1000
});
}
s = eDate.add(s, eDate.MONTH, 1);
}
return data;
})();
// create the Data Store
var store = Ext.create('Ext.data.Store', {
// destroy the store if the grid is destroyed
autoDestroy: true,
model: 'Employee',
proxy: {
type: 'memory'
},
data: data,
sorters: [{
property: 'start',
direction: 'ASC'
}]
});
// create the grid and specify what field you want
// to use for the editor at each column.
var grid = Ext.create('Ext.grid.Panel', {
store: store,
columns: [{
header: 'Name',
dataIndex: 'name',
flex: 1,
editor: {
// defaults to textfield if no xtype is supplied
allowBlank: false
}
}, {
header: 'Email',
dataIndex: 'email',
width: 160,
editor: {
allowBlank: false,
vtype: 'email'
}
}, {
xtype: 'datecolumn',
header: 'Start Date',
dataIndex: 'start',
width: 105,
editor: {
xtype: 'datefield',
allowBlank: false,
format: 'm/d/Y',
minValue: '01/01/2006',
minText: 'Cannot have a start date before the company existed!',
maxValue: Ext.Date.format(new Date(), 'm/d/Y')
}
}, {
xtype: 'numbercolumn',
header: 'Salary',
dataIndex: 'salary',
format: '$0,0',
width: 90,
editor: {
xtype: 'numberfield',
allowBlank: false,
minValue: 1,
maxValue: 150000
}
}, {
xtype: 'checkcolumn',
header: 'Active?',
dataIndex: 'active',
width: 60,
editor: {
xtype: 'checkbox',
cls: 'x-grid-checkheader-editor'
}
}],
renderTo: 'editor-grid',
width: 600,
height: 400,
title: 'Employee Salaries',
frame: true,
tbar: [{
text: 'Cancel editing Plugin',
handler: function(button) {
var myGrid = button.up('grid');
var myPlugin = myGrid.getPlugin('rowediting')
myPlugin.cancelEdit();
console.log(myPlugin);
}
}],
plugins: [{
clicksToMoveEditor: 1,
autoCancel: false,
ptype: 'rowediting',
pluginId: 'rowediting'
}]
});
});

grid loadmask won't disappear while using PagingMemoryProxy

I am trying to create a grid with store having PagingMemoryProxy.
Pagination is working and I can see as well as change all pages
but the loadmask won't disappear so I am not able to edit the grid data.
here is my code
Ext.require('Ext.ux.data.PagingMemoryProxy');
var data = {
Accounts: [{
id: 1,
name: 'Ed Spencer'
}, {
id: 2,
name: 'Abe Elias'
}, {
id: 3,
name: 'Tom Elias'
}]
};
Ext.define('Account', {
extend: 'Ext.data.Model',
fields: [{
name: 'id',
type: 'string'
}, {
name: 'name',
type: 'string'
}]
});
var store = Ext.create('Ext.data.Store', {
storeId: 'myStore',
pageSize: 2,
model: 'Account',
data : data,
proxy: {
type: 'pagingmemory',
reader: {
type: 'json',
root: 'Accounts'
}
},
});
var pagingBar = new Ext.PagingToolbar({
store: store,
displayInfo: true,
displayMsg: 'Displaying Accounts {0} - {1} of {2}',
emptyMsg: "No Accounts to display"
});
var grid = new Ext.create('Ext.grid.Panel', {
title: 'Accounts',
store: store,
columns: [{
header: 'Id',
dataIndex: 'id',
editor: 'textfield'
}, {
header: 'Name',
dataIndex: 'name',
flex: 1,
editor: {
xtype: 'textfield',
allowBlank: false
}
}],
plugins: [
Ext.create('Ext.grid.plugin.RowEditing', {
clicksToEdit: 1,
pluginId: 'rowEditing'
})],
height: 200,
width: 400,
loadMask: false,
renderTo: "editor-grid",
bbar: pagingBar
});
Store load event is getting fired and I can see greyed out data behind the loading mask
Firbug is showing no error.
I am using Extjs 4.1.3. Any idea what's the problem.
Thanks in advance
Looks like a known bug, think its fixed in Extjs 4.2.1
As a temporary fix, you can hide the mask 'on store load' using
grid.getView().setLoading(false);
Sample here : https://fiddle.sencha.com/#fiddle/1v9

Extjs getting the `formpanel` that is created dynamically from button click

I have ExtJS View-Port panel, that contain center panel, that contain tablpanel, in which I have added gridpanel in one tab, on this I have put Add Person button in tbar of , that will add a new tab of a formpanel, in its Reset button, I am not able to access Form to reset it.
Do any body have faced same issue?
Please help how to get it working.
Ext.onReady(function() {
// Ext.get(document.body, true).toggleClass('xtheme-gray');
var myBorderPanel = new Ext.Viewport({
title: 'Software Releases',
// renderTo: document.body,
renderTo: Ext.getBody(),
layout: 'border',
id: 'main',
items: [{
title: 'Center Region',
region: 'center', // center region is required, no width/height specified
tbar: [{
text: 'Add person', // only when user have write priovilege.
handler: function() {
var tabpanel = Ext.getCmp('main').findById('tabs');
var wtab = tabpanel.add({
// // var addrelease_win = new Ext.Window({
url: 'reledit-submit.json',
id: 'addform0',
// height: 300, width: 400,
layout: 'form',
frame: true,
title: 'Add New Release',
closable: true,
items: [{
xtype: 'textfield',
fieldLabel: 'Name'
}],
buttons: [{
text: 'Save',
scope: wtab,
handler: function() {
wtab.getForm().submit({
success: function(f, a) {
Ext.Msg.alert('Success', 'It worked');
},
failure: function(f, a) {
Ext.msg.alert('Warnning', 'Error');
}
});
}
}, {
text: 'Reset',
scope: wtab,
handler: function() {
// Ext.getCmp('addform0').getForm().reset();
// tabpanel.getActiveTab.reset();
// Ext.getCmp('main').findById('addform').getForm().reset();
// this.getForm().reset();
// this.getForm().reset();
// Ext.Msg.alert('sdfsd', 'asdfsd ' + Ext.getCmp('addform0').getValue() + ' sdfsd');
this.findById('addform0').getForm().reset();
// Ext.Msg.alert('sdfsd', 'asdfsd ');
}
}]
});
// addrelease_win.show();
tabpanel.activate(tabpanel.items.length - 1);
}
}],
xtype: 'tabpanel',
id: 'tabs',
activeTab: 0,
items: [{
title: 'Data',
xtype: 'editorgrid',
store: store,
stripeRows: true,
// autoExpandColumn: 'title',
columns: [{
header: "Name",
dataIndex: "name",
width: 50,
sortable: true
}, {
header: "DOB",
dataIndex: "dob",
sortable: true
}]
}],
margins: '5 5 0 0',
})
})
});
Doesn't wtab.getForm().reset(); work?
If not, use this.ownerCt to get to the buttons container and then just walk up the chain until you get to a point where you can access the form.
UPDATE
The real problem is that its a Panel with a form layout that is created and not a FormsPanel.
Change layout:'form' into xtype:'form' and .getForm() should work.

Categories