ExtJS reloading store on button click event with different parameter - servlets

I am new to ExtJs and I am using ExtJs4.
Now As shown in below image, There is one textfield named keywords, What I want to do is When I click on the button it will pass data of textfield to servlet and display resulted record in grid.
Now I have no idea how to do this. I am receiving JSON data response from servlet but don't know how to reload the store and refresh the grid.
Below is code for my store and grid.
Ext.define("Post", {
extend: 'Ext.data.Model',
proxy: {
type: 'ajax',
url: '/ezdi/searchServlet',
method: 'POST',
reader: {
type: 'json',
root: 'rows'
//,totalProperty: 'totalCount'
}
},
fields: [{
name: 'docid',
mapping: 'docid'
}, {
name: 'mrn',
mapping: 'mrn'
}, {
name: 'fname',
mapping: 'fname'
}]
});
var gridDataStore = Ext.create('Ext.data.Store', {
model: 'Post'
});
// Data store for grid end
Ext.define('Ezdi.Grid', {
extend: 'Ext.grid.GridPanel',
alias: 'widget.ezdigrid',
initComponent: function() {
var config = {
store: gridDataStore,
columns: [{
header: "DocID",
width: 100,
sortable: true,
dataIndex: 'docid'
}, {
header: "MRN",
width: 100,
sortable: true,
dataIndex: 'mrn'
}, {
header: "FirstName",
width: 100,
sortable: true,
dataIndex: 'fname'
}],
viewConfig: {
forceFit: false,
autoLoad: false
},
loadMask: true
};
}
});

You could use:
{
xtype: 'button',
text: 'Search',
handler: function() {
store.clearFilter(); //clear previous search value
var searchValue = Ext.getCmp("textFieldId").getValue(); //get new value
store.load().filter('jsonGridFielName', searchValue); //load filtered data
}
}
And for for multiple textfield search:
//FILTERS
var searchValue1 = Ext.getCmp("textFieldId1").getValue(); //value1
var searchValue2 = Ext.getCmp("textFieldId2").getValue(); //value2
var noValue = "0000xxxx"; //no Value, for empty field, use value that you are sure it is not going to be searched!!!
var clear = store.clearFilter(); //shortcut
if (!searchValue1 && !searchValue2) {
clear;
store.load().filter("jsonGridFielName1", noValue);
} else if (searchValue1) {
clear;
store.load().filter('jsonGridFielName1', searchValue1);
//...else if(searchValue n...)...
} else {
clear;
store.load().filter('jsonGridFielName2', searchValue2);
}

ezdigrid.js
// Data store for grid start
Ext.define("Post", {
extend: 'Ext.data.Model',
proxy: {
type: 'ajax',
url: '/ezdi/searchServlet',
method: 'GET',
reader: {
type: 'json',
root: 'rows'
//,totalProperty: 'totalCount'
}
},
fields: [{
name: 'docid',
mapping: 'docid'
}, {
name: 'mrn',
mapping: 'mrn'
}, {
name: 'fname',
mapping: 'fname'
}]
});
var gridDataStore = Ext.create('Ext.data.Store', {
// pageSize: 10,
model: 'Post'
});
// Data store for grid end
Ext.define('Ezdi.Grid', {
extend: 'Ext.grid.GridPanel',
alias: 'widget.ezdigrid',
initComponent: function() {
var config = {
store: gridDataStore,
columns: [{
//id:'ms',
header: "DocID",
width: 100,
sortable: true,
dataIndex: 'docid'
}, {
header: "MRN",
width: 100,
sortable: true,
dataIndex: 'mrn'
}, {
header: "FirstName",
width: 100,
sortable: true,
dataIndex: 'fname'
}],
viewConfig: {
forceFit: false,
autoLoad: false
},
loadMask: true
}; // eo config object
// apply config
Ext.apply(this, Ext.apply(this.initialConfig, config));
// call parent
Ezdi.Grid.superclass.initComponent.apply(this, arguments);
// load the store at the latest possible moment
this.on({
afterlayout: {
scope: this,
single: true,
fn: function() {
this.store.load({
params: {
start: 0,
limit: 30
}
});
}
}
});
} // eo function initComponent
});
demo.html
//handler for button click event
fbar: [{
xtype: 'button',
text: 'Search',
handler: function() {
var value = Ext.getCmp('_keyword').getValue(); //_keyword is textField
gridDataStore.load().filter('keywords', value);
}
}]
MyServlet
keyword = request.getParameter("keywords");
//code for quesry processing

Use extraParams in your model.
extraParams: {
keywords: 'your-value'
}
Put following code in your button click handler.
gridDataStore.proxy.extraParams.keywords = 'new value';
gridDataStore.load();

Related

EXTJS 5.0: Infinite Grid scrolling not working with extraParams in store

I am using ExtJS 5.0.1. I have a grid which does not autoLoad. Once the store is manually loaded by using the click button in TopBar, the grid receives records.
I am trying to implement infinite scroll on this grid. My store has extra params that need to be passed to the backend in order to get the records. After the first page is loaded, for the second page, no extra params are passed to the backend. How can I correct this?
My store looks as follows ->
Ext.define('MyStore', {
// extend: 'Ext.data.BufferedStore',
extend: 'Ext.data.Store',
model : 'MyModel',
remoteSort: true,
buffered: true,
leadingBufferZone: 10,
trailingBufferZone: 10,
pageSize: 100,
proxy: {
type : 'rest',
format: 'json',
url : '/myApp/list',
extraParams: {
fromDate: '',
toDate: ''
},
reader: {
type: 'json',
rootProperty: 'data',
totalProperty: 'totalCount'
}
}
});
My Grid looks as follows-->
Ext.define('MyGridl', {
extend: 'Ext.grid.Panel',
requires: [
'MyStore'
],
layout: 'fit',
loadMask: true,
viewConfig: {
preserveScrollOnRefresh: true
},
initComponent: function() {
this.id = 'myGrid';
this.store = new MyStore();
this.callParent(arguments);
},
overflowY: 'auto',
frame: true,
columns: [{
xtype: 'rownumberer',
width: 50,
sortable: false
},{
text: 'Column1',
dataIndex: 'Col1',
flex: 1
},{
text: 'Column2',
dataIndex: 'Col2',
flex: 1
}
],
plugins: [
{
ptype: 'bufferedrenderer',
trailingBufferZone: 10,
leadingBufferZone: 10,
scrollToLoadBuffer: 10
}
],
tbar: {
items: [{
xtype : 'datefield',
id : 'fromDate',
emptyText: 'Enter From Date',
listeners : {
render : function(datefield) {
datefield.setValue(Ext.Date.add(new Date(), Ext.Date.DAY, -5));
}
}
},{
xtype : 'datefield',
id : 'toDate',
emptyText: 'Enter To Date',
listeners : {
render : function(datefield) {
datefield.setValue(new Date());
}
}
},{
xtype: 'button',
text: 'Filter by Date',
style: {
marginLeft: '15px'
},
scope: this,
handler: function(me){
var store = Ext.getStore('myStore'),
fromDay = me.up().down('#fromDate').getValue(),
toDay = me.up().down('#toDate').getValue();
store.removeAll();
store.load({
params:{
fromDate: fromDay,
toDate: toDay
}
});
}
}
]
}
});
I fixed this issue by adding
store.removeAll();
store.currentPage = 1;
store.getProxy().setExtraParam("fromDate", fromDay);
store.getProxy().setExtraParam("toDate", toDay);
store.load();

ExtJS4.2 Grid Filter Leaves empty Rows with Paging - NewbieQ

I have tried various ways to refresh the grid but everything I try doesn't work. Do I refresh the Grid or do I load the store??? You can see that the paging tool bar is still showing 50 pages after the filtering. If there are no dates on a given pag and it is empty then it will disable the tool bar and paging doesn't work after that page un less you refresh the browser and skip over the empty page. So, in my case page 15 has no rows so it breaks when u hit next and get that page. If you type in the page number 16 then all is good until you hit another's empty page.
My datepicker is in my viewport below and I have tried refreshing the gird and loading the store as well as other things which mostly result in undefined error. Not sure where to start with this one so I will show my code and screen shots below:
BEFORE DATE SELECTION:
AFTER DATE SELECTION:
STORE:
Ext.define('AM.store.Users', {
extend: 'Ext.data.Store',
model: 'AM.model.User',
autoLoad: true,
autoSync:true,
pageSize:50,
proxy:
{
type: 'ajax',
//extraParams :{limit:1000},
api:
{
read: 'http://192.168.0.103/testit/dao_2.cfc?method=getContent',
update: 'http://192.168.0.103/testit/dao_2-post.cfc?method=postContent'
},
reader:
{
type: 'json',
root: 'data',
successProperty: 'success',
totalProperty : 'dataset',
remoteFilter : true
},
listeners:
{
// stuff goes here maybe??
}
}
});
GRID PANEL:
Ext.define('AM.view.user.List' ,{
extend: 'Ext.grid.Panel',
alias: 'widget.userlist',
title: 'All Users',
store: 'Users',
//buffered: true,
plugins:[Ext.create('Ext.grid.plugin.RowEditing', {clicksToEdit: 2})],
dockedItems: [{ xtype: 'pagingtoolbar',
store: 'Users',
dock: 'bottom',
displayMsg: 'Displaying Records {0} - {1} of {2}',
displayInfo: true}],
initComponent: function() {
this.columns = [
Ext.create('Ext.grid.RowNumberer',
{
resizable: true,
resizeHandles:'all',
align: 'center',
minWidth: 35,
maxWidth:50
}),
{
header: 'Name',
dataIndex: 'message_id',
flex: 1,
editor:'textfield',
allowBlank: false,
menuDisabled:true
},
{
header: 'Email',
dataIndex: 'recip_email',
flex: 1,
editor:'textfield',
allowBlank: false,
menuDisabled:true
},
{
header: 'Date Time',
dataIndex: 'unix_time_stamp',
width: 120,
menuDisabled:true,
// submitFormat: 'd/m/Y',
renderer: Ext.util.Format.dateRenderer('m/d/Y'),
field:{ xtype:'datefield',
autoSync:true,
allowBlank:false,
editor: new Ext.form.DateField(
{format: 'm/d/y'}) }
}];
this.callParent(arguments);
},
});
VIEWPORT:
Ext.Loader.setConfig({enabled:true});
Ext.application({
requires: ['Ext.container.Viewport'],
name: 'AM',
appFolder: 'app',
controllers: ['Users'],
launch: function() {
Ext.create('Ext.container.Viewport', {
layout: 'border',
items:[{
region: 'center',
itemId:'centerPanelRegion',
title:'The Title',
xtype: 'tabpanel',
hidden: true,
activeTab: 0,
items:[{
xtype: 'userlist',
listeners:
{
select: function(selModel, record, index, options)
{
// do something with the selected date
console.log('select');
},
add: function(selModel)
{
// do something with the selected date
console.log('add - init2.js');
},
afterrender:function(selModel)
{
// do something with the selected date
console.log('afterrender - userlist(init2.js)');
},
beforerender:function(selModel)
{
// do something with the selected date
console.log('beforerender - userlist(init2.js)');
}
}
}]
},
{
region: 'west',
itemId:'westPanelRegion',
hidden: true,
layout:'fit',
xtype: 'tabpanel',
activetab:0,
collapsible:false,
split: false,
title: 'The Title',
width:178,
maxWidth:400,
height: 100,
minHeight: 100,
items:[{
title: 'Tab 1',
xtype:'panel',
items:
[{
xtype: 'datepicker',
itemId:'datePickerFld',
listeners:{
beforerender: function(){
console.log('datepicker - beforerender(init2.js)');
var store = Ext.getStore('dates');
store.load({callback: function(){
console.log('datepicker - callback(init2.js');
console.log(store.data.items[999].data.recip_email);
console.log(store.data.items[999].data.unix_time_stamp);
}
})
}
},
handler: function(picker, date)
{
// do something with the selected date
console.log('date picker example in init2.js' + Ext.Date.format(date,'m/d/Y'));
// get store by unique storeId
var store = Ext.getStore('Users');
// clear current filters
store.clearFilter(true);
// filter store
Ext.encode(store.filter("unix_time_stamp", Ext.Date.format(date,'m/d/Y')));
//store.load();
//store.sync();
}
}]
},
{
title: 'Tab 2',
html: 'ers may be added dynamically - Others may be added dynamically',
}]
}]
});
}
});
CONTROLLER:
Ext.define('AM.controller.Users', {
extend: 'Ext.app.Controller',
stores:['Users', 'dates'],
models:['User', 'date'],
views: ['user.List','user.Edit'],
init: function() {
Ext.getStore('dates').addListener('load',this.ondatesStoreLoad, this);
this.control(
{
'viewport > userlist':
{
itemdblclick: this.editUser,
},
'useredit button[action=save]':
{
click: this.updateUser
}
});
},
// ---------- handler Function declarations -------------
ondatesStoreLoad: function(me,records,success)
{
// ------ Gets the dates from dates store and loads an array
var store = this.getStore('dates');
sendDataArray = [];
store.each(function(record){
var recordArray = [record.get("unix_time_stamp")];
sendDataArray.push(recordArray);
});
// ------ Set DatePicker Bullshit right fucking here --------//
var dtFld = Ext.ComponentQuery.query('#datePickerFld')[0];
dtFld.setDisabledDates(["^(?!"+sendDataArray.join("|")+").*$"]);
dtFld.setMaxDate(new Date());
dtFld.setMinDate(new Date('05/01/2013'));
var wstPnlReg = Ext.ComponentQuery.query('#westPanelRegion')[0];
wstPnlReg.show();
var ctrPnlReg = Ext.ComponentQuery.query('#centerPanelRegion')[0];
ctrPnlReg.show();
// var grid = Ext.widget('userlist');
},
onUsersStoreDataChange: function(me)
{
//console.log('Hey the store data just changed!');
},
editUser: function(grid, record)
{
var view = Ext.widget('useredit');
view.down('form').loadRecord(record);
},
updateUser: function(button)
{
var win = button.up('window'),
form = win.down('form'),
record = form.getRecord(),
values = form.getValues();
record.set(values);
win.close();
this.getUsersStore().sync();
},
});
UPDATED VIEWPORT: Changes made only in datepicker handler
Ext.Loader.setConfig({enabled:true});
Ext.application({
requires: ['Ext.container.Viewport'],
name: 'AM',
appFolder: 'app',
controllers: ['Users'],
launch: function() {
Ext.create('Ext.container.Viewport', {
layout: 'border',
items:[{
region: 'center',
itemId:'centerPanelRegion',
title:'The Title',
xtype: 'tabpanel',
hidden: true,
activeTab: 0,
items:[{
xtype: 'userlist',
listeners:
{
select: function(selModel, record, index, options)
{
// do something with the selected date
console.log('select');
},
add: function(selModel)
{
// do something with the selected date
console.log('add - init2.js');
},
afterrender:function(selModel)
{
// do something with the selected date
console.log('afterrender - userlist(init2.js)');
},
beforerender:function(selModel)
{
// do something with the selected date
console.log('beforerender - userlist(init2.js)');
}
}
}]
},
{
region: 'west',
itemId:'westPanelRegion',
hidden: true,
layout:'fit',
xtype: 'tabpanel',
activetab:0,
collapsible:false,
split: false,
title: 'The Title',
width:178,
maxWidth:400,
height: 100,
minHeight: 100,
items:[{
title: 'Tab 1',
xtype:'panel',
items:
[{
xtype: 'datepicker',
itemId:'datePickerFld',
listeners:{
beforerender: function(){
console.log('datepicker - beforerender(init2.js)');
var store = Ext.getStore('dates');
store.load({callback: function(){
console.log('datepicker - callback(init2.js');
console.log(store.data.items[999].data.recip_email);
console.log(store.data.items[999].data.unix_time_stamp);
}
})
}
},
handler: function(picker, date)
{
// do something with the selected date
console.log('date picker example in init2.js' + Ext.Date.format(date,'m/d/Y'));
// get store by unique storeId
var store = Ext.getStore('Users');
// clear current filters
store.clearFilter(true);
// filter store
store.filter("unix_time_stamp", Ext.Date.format(date,'m/d/Y'));
// Load the store
store.load();
}
}]
},
{
title: 'Tab 2',
html: 'ers may be added dynamically - Others may be added dynamically',
}]
}]
});
}
});
This line is likely causing the issues.
Ext.encode(store.filter("unix_time_stamp", Ext.Date.format(date,'m/d/Y')));
I'm not sure why you are calling Ext.encode on whatever store.filter returns, but I don't think you want to do that (and it is likely causing the undefined errors).
As for the paging toolbar not updating the current count, it is likely you just aren't returning the correct information in your server response when updating the store. The server response should include the total number of records. According to the docs for Ext.toolbar.Paging, http://docs.sencha.com/extjs/4.2.2/#!/api/Ext.toolbar.Paging:
The packet sent back from the server would have this form:
{
"success": true,
"results": 2000,
"rows": [ // ***Note:** this must be an Array
{ "id": 1, "name": "Bill", "occupation": "Gardener" },
{ "id": 2, "name": "Ben", "occupation": "Horticulturalist" },
...
{ "id": 25, "name": "Sue", "occupation": "Botanist" }
]
}

How to perform custom paging in Ext Grid

I have following Ext Grid,
Ext.onReady(function () {
var dataStore = new Ext.data.JsonStore({
proxy: {
type: 'ajax',
url: 'Default.aspx/CustomerData', //'web.aspx',
headers: { 'Content-type': 'application/json' },
reader: {
type: 'json',
root: 'd',
totalProperty: 'totalCount'
}
},
fields: [
{ name: 'firstname', type: 'string' },
{ name: 'lastname', type: 'string' },
{ name: 'age', type: 'string' },
{ name: 'phone', type: 'string' }
],
pageSize: 10
});
dataStore.load({ params: { start: 0, limit: 25} });
var myGrid1 = new Ext.grid.GridPanel({
id: 'customerslist',
store: dataStore,
columns: [
{ id: "firstname", header: "First Name", width: 100, dataIndex: "firstname", sortable: true },
{ header: "Last Name", width: 100, dataIndex: "lastname", sortable: true },
{ header: "Age", width: 100, dataIndex: "age", sortable: true },
{ header: "Phone", width: 100, dataIndex: "phone", sortable: true }
],
autoLoad: false,
stripeRows: true,
autoHeight: true,
width: 450,
height: 300,
dockedItems: [{
xtype: 'pagingtoolbar',
store: dataStore,
dock: 'bottom',
displayInfo: true
}],
renderTo: 'grid1'
});
});
I have following server side code for custom paging,
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true, XmlSerializeString = false)]
public static List<tblCustomerList> CustomerData(int rowSize, int pageNumber)
{
DataGridEntities _dbContext = new DataGridEntities();
//Code for custom paging
Customer customer = new Customer();
customer.TotalRecords = //code for total record count
customer.Details = //fetch record based on page number and page size
return customer.Details;
}
}
How can I achieve custom Paging in this.
Paging is done with start and limit per default. And if you don't want to rewrite the whole chain I recommend you to leave it as it is an simply add two more params, in your case
dataStore.load({
params: {
rowSize: dataStore.pageSize,
pagenNumber: dataStore.currentPage || 1
}
});
In addition you will need either a custom paging navigation, a customized version of the paging toolbar or a beforeload eventhandler like this:
function(store,operation,eo){
operation.params: {
rowSize: store.pageSize,
pagenNumber: store.currentPage +1 // I assume that this was not updated before a successful load
}
}
This is untested and should show you how it can be done.

Having some trouble reading JSON response

I make an ajax request to the servlet that returns the result of a database query.
I can see with firebug the response and I want to put these results in a list (or other..) that I have already created.
I tried to read this post but it didn't help me..
Code:
this is the ajax request:
Ext.Ajax.request({
url: '/VIProject/Container',
success: function (action){alert('Lista caricata!'); console.debug(action); },
failure: function (){alert('Errore nel caricamento...');},
headers: {
'my-header': 'foo'
},
params: { action: "GETCONTAINERLIST" }
});
response from servlet(firebug):
{"message":"OK","container":[{"idOrdine":"1","numLotto":"123"},{"idOrdine":"2","numLotto":"321"},{"idOrdine":"3","numLotto":"876"}],"success":true}
list:
var listView = Ext.create('Ext.grid.Panel', {
width:425,
height:250,
id: 'lista',
collapsible:true,
title:'Simple ListView <i>(0 items selected)</i>',
store: //???
multiSelect: true,
viewConfig: {
emptyText: 'No images to display'
},
columns: [{
text: 'idOrdine',
flex: 15,
sortable: true,
dataIndex: 'idOrdine'
},{
text: 'Last Modified',
flex: 20,
sortable: true,
dataIndex: 'numLotto'
}]
});
How can I do?
I've modified your code to use a store:
Ext.define('MyModel', {
extend: 'Ext.data.Model',
fields: ['idOrdine', 'numLotto']
})
var listView = Ext.create('Ext.grid.Panel', {
width:425,
height:250,
id: 'lista',
collapsible:true,
title:'Simple ListView <i>(0 items selected)</i>',
store: store: {
model: MyModel,
autoLoad: true,
proxy: {
type: 'ajax',
url: '/VIProject/Container',
reader: {
type: 'json',
root: 'container'
}
}
},
multiSelect: true,
viewConfig: {
emptyText: 'No images to display'
},
columns: [{
text: 'idOrdine',
flex: 15,
sortable: true,
dataIndex: 'idOrdine'
},{
text: 'Last Modified',
flex: 20,
sortable: true,
dataIndex: 'numLotto'
}]
});
Even in this way it works:
var proxy=new Ext.data.HttpProxy({url:'/VIProject/Container'});
var reader=new Ext.data.JsonReader({},[
{name: 'idOrdine', mapping: 'idOrdine'},
{name: 'numLotto', mapping: 'numLotto'}
]);
var store=new Ext.data.Store( {
proxy:proxy,
reader:reader
});
store.load();
I tried in every way.. but i don't know what to do!

kendogrid batch edit appending row causes to post data

This code populates datagrid with json formated data received from /api/notes/ by tornado app...
$(document).ready(function () {
dataSource = new kendo.data.DataSource({
pageSize: 10,
autoSync: true,
transport: {
read: {
url: '/api/notes/',
dataType: 'json',
type: 'GET'
},
create: {
url: '/api/notes/',
dataType: 'json',
type: 'POST'
},
update: {
url: '/api/notes/',
dataType: 'json',
type: 'PUT'
}
},
schema: {
data: function(reply) { return reply.rows; },
model: {
id: "id",
fields: {
id: { type: "string" },
name: { type: "string" },
author: { type: "string" },
}
}
},
});
$("#grid").kendoGrid({
dataSource: dataSource,
navigatable: true,
pageable: true,
height: 300,
editable: true,
toolbar: ["create", "save", "cancel"],
columns: [
{ field: "id", title: "ID", width: 150 },
{ field: "name", title: "Book", width: 150 },
{ field: "author", title: "Author", width: 100 },
{ command: "destroy", title: " ", width: 110 }
],
});
});
if I click create instead of popping up a row, like here a post triggered with empty data parameter, what's wrong here
Try it with autoSync removed or set to false on the DataSource. According to the docs:
Enables (true) or disables (false) the automatic invocation of the sync() method for each change made.
So I think when you try to insert the row, it immediately puts it into the DataSource, causing it to do a sync(). The demo you linked to doesn't specify autoSync either.

Resources