PDA

View Full Version : DWRProxy improved



loeppky
22 Jan 2008, 12:32 PM
This is for Ext 2.x. Please see http://www.extjs.com/forum/showthread.php?p=343185 for the Ext 3.x compatible release.

DwrProxy is now part of a larger ExtJsWithDwr project on GitHub (http://github.com/BigLep/ExtJsWithDwr/) (see form post (http://extjs.com/forum/showthread.php?t=69349)).

What does this mean?

DWRProxy has been renamed to DwrProxy (although DWRProxy) is provided for backwards compatibility.
The code is publically available and easy to check out.
Official examples have been created that demonstrate DwrProxy in action. They're part of the GitHub project or can be seen here: http://biglep.s156.eatj.com/extJsWithDwrExamples/.
Now that all this overhead is taken care for DwrProxy, work on Ext 3.x support will come next week.



Where can I find the code?
http://github.com/BigLep/ExtJsWithDwr/blob/v2/source/data/DwrProxy.js


Why was this class created?
I found Axel's DWRProxy class in this thread (http://extjs.com/forum/showthread.php?t=19529) a great starting point for enabling me to have a combobox load data through DWR. There were a couple of issues though that I experienced and saw in the original thread and others. Those issues were:

Not compatible with Ext provided readers (e.g. ArrayReader and JSONReader).
Arguments to the DWR function weren't guaranteed to be in the required order needed for the backend.


There were the additional minor issues that:

The beforeload event wasn't "vetoable" like it was with every proxy.
DWRProxy wasn't in the Ext.ux namespace.



Updates:

2/21/08 - Fixed bug with exceptionHandler. Also corrected the spacing/indentation.
3/7/08 - Fixed additional bug with exceptionHandler.
3/12/08 - Fixed additional bug with exceptionHandler.
5/24/09 - Renamed to DwrProxy (DWRProxy is added for backwards compatiblity) and posted project on GitHub.

loeppky
22 Jan 2008, 12:37 PM
Here

Artem
23 Jan 2008, 6:40 AM
done like you wrote and got exception
Ext.ux.data has no properties
proxy: new Ext.ux.data.DWRProxy({

can you help ?

Timido
23 Jan 2008, 7:01 AM
I have a DWR remote method that returns a List of Person [name, surname].
I'd like to show them in a GridPanel.

If I load the data thru a Store like this:



var myReader = new Ext.data.ArrayReader({}, [
{name: 'name'},
{name: 'surname'}
]);

var myStore = new Ext.data.Store({
data: myPeople,
reader: myReader
});


it works fine.

But if I use a proxy like this:



var dwrproxy = new Ext.ux.data.DWRProxy({
dwrFunction: MyDwrService.getPersone,
listeners: {
'beforeload': function(dataProxy, params){}
}
});



It does not work, that is, the grid gets rendered, but without any data.
I see the people data list coming from the server passing thru my firfox firebug, and actually the the server gets called.

What is wrong?
I tried to use both this version of DwrProxy and the previous posted one, but none of them seems to work properly. Where am I wrong at ?

thank you

loeppky
23 Jan 2008, 10:44 AM
done like you wrote and got exception
Ext.ux.data has no properties
proxy: new Ext.ux.data.DWRProxy({


Artem, the fact that "Ext.ux.data has no properties" suggests that you didn't create the namespace. Did you copy the first line of the DWRProxy class post: "Ext.namespace("Ext.ux.data");"?

loeppky
23 Jan 2008, 11:11 AM
Timido,

What is the method signature of MyDwrService.getPersone? What parameters does it take, and what does it return?

Also, note that your "beforeload" listener in the DWRProxy isn't doing anything, and thus is unnecessary.

SmartChow
23 Jan 2008, 7:52 PM
Great job!
but i have some troubles
could you tell me how to pass param by queryParam
how to use the property of queryParam
thanks

Artem
23 Jan 2008, 10:07 PM
fix my exception, was in wrong path to dwrproxy.js.
cound you also say can i put data in GridPanel? with proxy

Timido
24 Jan 2008, 1:36 AM
Timido,

What is the method signature of MyDwrService.getPersone? What parameters does it take, and what does it return?

Also, note that your "beforeload" listener in the DWRProxy isn't doing anything, and thus is unnecessary.

hi, here is the method sign:




public List getPersone() {

List persone = new ArrayList();

Persona p1 = new Persona("john", "smith");
Persona p2 = new Persona("andy", "garcia");
Persona p3 = new Persona("ricky", "martin");
Persona p4 = new Persona("ricky", "martin");
persone.add(p1);
persone.add(p2);
persone.add(p3);
persone.add(p4);

log.info("GET PERSONE");
return persone;

}



I cant get the list to be loaded into the grid :(
Thank you for any hints :)

loeppky
24 Jan 2008, 2:33 PM
could you tell me how to pass param by queryParam
how to use the property of queryParam

SmartChow: this is real easy to do. In the original example, if you defined your combobox to have a queryParam of 'differentQueryParam', then the "beforeload" listener would look like:



'beforeload': function(dataProxy, params){
// setting the args that will get passed to the DWR function
params[dataProxy.loadArgsKey] = ['loeppkyIsMyUserId', params.differentQueryParam];
}

loeppky
24 Jan 2008, 2:37 PM
cound you also say can i put data in GridPanel? with proxy

Artem: your question wasn't exactly clear, but if you are asking "can I use DWRProxy with a GridPanel', then the answer is yes. You can use DWRProxy anywhere that expects a Ext.data.DataProxy, including GridPanel. Remember, a Ext.data.Store "stores" Ext.data.Records. It uses its proxy to fetch data, and it uses its reader to create records from the fetched data.

loeppky
24 Jan 2008, 2:42 PM
I cant get the list to be loaded into the grid :(
Thank you for any hints :)


Timido: your Java method has a return type of List<Persona>. Thus the DWR call will be returning an array of JSON objects. You will thus need to use and configure a JSONReader to convert your array of objects into Ext.data.Records. Are you using a JSONReader?

Artem
24 Jan 2008, 9:52 PM
"can I use DWRProxy with a GridPanel"


var ObjectJSON = Ext.data.Record.create([
{name: "id", type: "int"},
{name: "name", type: "string"}
]);
var ObjectJSONReader = new Ext.data.JsonReader({
id: "id",
totalProperty: "totalSize",
root: "data"
}, ObjectJSON);


var ds = new Ext.data.Store({
proxy: new Ext.ux.data.DWRProxy({
dwrFunction: DWRcallFunction,
listeners: {
"beforeload" : function(dataProxy, params) {
params[dataProxy.loadArgsKey] = DWRcallParams;
}
}
}),

reader: ObjectJSONReader
});
var colModel = new Ext.grid.ColumnModel([
//{id: "id", header: "id", dataIndex: "id", sortable: true},
{header: "name", dataIndex: "name", sortable: true}
]);
var form = new Ext.form.FormPanel({
id: "item-search-form" + div,
autoScroll: true,
frame: true,
items: [{
anchor: "100%",
items: {
xtype: "grid",
ds: ds,
cm: colModel,
border: true
}
}],
renderTo: Ext.getBody()
});


dwr method:


public ListRange getRegions(String name) throws ServiceException {
Collection<Region> list = null;
try {
list = addressMgmtService.getAllRegionsByName(name);
} catch (ServiceException e) {
list = new ArrayList<Region>();
}

ListRange listRange = new ListRange();
Object[] data = new Object[list.size()];
int c = 0;
for (Region region : list) {
data[c++] = new ObjectAjax(region.getId().intValue(), region.getName());
}

listRange.setData(data);
listRange.setTotalSize(5555);

return listRange;
}

ListRange


public class ListRange implements Serializable {

private static final long serialVersionUID = 1L;

private Object[] data;
private int totalSize;

public Object[] getData() {
return data;
}

public void setData(Object[] data) {
this.data = data;
}

public int getTotalSize() {
return totalSize;
}

public void setTotalSize(int totalSize) {
this.totalSize = totalSize;
}
}

dwr method correctry return data, but if grid was empty on data come, it didnt fetch as well. and if some data was in grid

var insData = [
{ id: 1, name: ''},
{ id: 2, name: ''},
{ id: 3, name: ''},
{ id: 4, name: ''},
{ id: 5, name: ''},
{ id: 6, name: ''},
{ id: 7, name: ''} ];

ds.loadData({data: insData, totalSize:7});
ds.load();

then returned data fetching good.
why, whats wrong?

Timido
25 Jan 2008, 9:02 AM
Timido: your Java method has a return type of List<Persona>. Thus the DWR call will be returning an array of JSON objects. You will thus need to use and configure a JSONReader to convert your array of objects into Ext.data.Records. Are you using a JSONReader?

Hi,
I was not using a JSONReader...

I tried with a JSONReader like this:



var myReader = new Ext.data.JsonReader({
//totalProperty: "results",
root: "returnedObject"
//id: 'id'
}, Persona );



but it does not work...
The "returnedObject" in root: "returnedObject" is the object where I put the List of Persona in:




public DWRReturn getPersone() {

DWRReturn ret = this.getDwrReturn();

List persone = new ArrayList();

Persona p1 = new Persona("john", "smith");
Persona p2 = new Persona("andy", "garcia");
Persona p3 = new Persona("ricky", "martin");
Persona p4 = new Persona("ricky", "martin");
persone.add(p1);
persone.add(p2);
persone.add(p3);
persone.add(p4);

log.info("GET PERSONE");

ret.setReturnedObject(persone);
ret.setTotalSize(persone.size());
return ret;

}




Do you have some example ?

thank you :)

loeppky
25 Jan 2008, 2:23 PM
Artem and Timido: I am working on putting an example together that works with the JSONReader. I may not be able to get it out until Monday as I have a busy weekend.

Artem
27 Jan 2008, 8:42 PM
thank you

loeppky
29 Jan 2008, 9:16 AM
I'm still swamped here at work with annual reviews, upcoming vacation, and the end my team's sprint. As a result, I haven't been able to complete this example. I will get to it as soon as I can.

Timido
30 Jan 2008, 9:53 AM
I'm still swamped here at work with annual reviews, upcoming vacation, and the end my team's sprint. As a result, I haven't been able to complete this example. I will get to it as soon as I can.

ok thanks :)

kaki
31 Jan 2008, 7:33 AM
But how can i get a dwr return string with EXT.Tree?

thank you!

~o)

loeppky
31 Jan 2008, 8:16 AM
Kaki: since Tree's don't use the store/proxy/reader paradigm, DWRProxy won't work with. I haven't looked into getting DWR to work with trees yet. That said, you should do a search for DWRTreeLoader. Here's a DWRTreeLoader class: http://extjs.com/forum/showthread.php?t=6217.

Timido: I am out of town Friday-Sunday, thus won't be able to finish off the example until early next week. I'm sorry about the delay. I'll get to it as soon as I can.

kaki
5 Feb 2008, 1:23 AM
Kaki: since Tree's don't use the store/proxy/reader paradigm, DWRProxy won't work with. I haven't looked into getting DWR to work with trees yet. That said, you should do a search for DWRTreeLoader. Here's a DWRTreeLoader class: http://extjs.com/forum/showthread.php?t=6217.

Timido: I am out of town Friday-Sunday, thus won't be able to finish off the example until early next week. I'm sorry about the delay. I'll get to it as soon as I can.


thanks a lot for loeppky,that article i have read,but it must be worked at jdk5.0.

how about some suggest for jdk1.42?

ka3S
7 Feb 2008, 5:55 AM
Hi loeppky,

I have tried your example DWRProxy improved, and I verified these links :


<link rel="stylesheet" type="text/css" href="/external/ext/resources/css/ext-all.css"/>

<!-- Ext dependencies -->
<script type="text/javascript" src="/external/ext/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="/external/ext/ext-all.js"></script>

<!-- Ext extension dependencies -->
<script type="text/javascript" src="/external/ext-extensions/source/data/DWRProxy.js"></script>

<!-- DWR dependencies -->
<script type="text/javascript" src="/dwr/interface/DWRProxySampleInterface.js"></script>
<script type="text/javascript" src="/dwr/engine.js"></script>

but with Firebug, I have the error :

Ext is not defined
Ext.onReady(function() {

What's the problem :-?

loeppky
7 Feb 2008, 9:19 AM
kaS3: "Ext not defined" means that Ext must not be loaded before you try and use it. Are you sure that my same "Ext.onReady" JavaScript code comes after your inclusion of "ext-base.js" and "ext-all.js"?

ka3S
7 Feb 2008, 10:57 PM
Yes, I verified it. I use the same source that you gived it in this thread (html page).

ka3S
7 Feb 2008, 11:05 PM
I have resolved the problem of 'Ext is not defined'. It was a wrong path for Ext dependencies.

Other question:
must I save the following code with the name DWRProxySampleInterface.js or DWRProxySampleInterface.java (:| ?


@RemoteProxy(name="DWRProxySampleInterface")
public class DWRProxySample {

@RemoteMethod
public static List<List<String>> getPossibleBusinessGroups(String userId, String query) {

List<List<String>> groupNames = new ArrayList<List<String>>();
List<String> groupName;

groupName = new ArrayList<String>();
groupName.add("group1");
groupNames.add(groupName);

groupName = new ArrayList<String>();
groupName.add("group2");
groupNames.add(groupName);

groupName = new ArrayList<String>();
groupName.add("group3");
groupNames.add(groupName);

return groupNames;
}
}

ka3S
8 Feb 2008, 2:35 AM
I have resolved the problem of 'Ext is not defined'. It was a wrong path for Ext dependencies.

Other question:
must I save the following code with the name DWRProxySampleInterface.js or DWRProxySampleInterface.java (:| ?


@RemoteProxy(name="DWRProxySampleInterface")
public class DWRProxySample {

@RemoteMethod
public static List<List<String>> getPossibleBusinessGroups(String userId, String query) {

List<List<String>> groupNames = new ArrayList<List<String>>();
List<String> groupName;

groupName = new ArrayList<String>();
groupName.add("group1");
groupNames.add(groupName);

groupName = new ArrayList<String>();
groupName.add("group2");
groupNames.add(groupName);

groupName = new ArrayList<String>();
groupName.add("group3");
groupNames.add(groupName);

return groupNames;
}
}

and which configuration must I do to let it work? (I use IntelliJ with struts, tomcat).

When I tried your provided example (and I verified the needed dependencies), I have the error : 'DWRProxySampleInterface is not defined'. What's the problem :-?

djiao
8 Feb 2008, 8:22 AM
loeppky, have you finished the grid example? Thanks!

loeppky
8 Feb 2008, 9:52 AM
ka3S: since the name of the Java class is "DWRProxySample", you should name the file "DWRProxySample.java". Also, I don't have the bandwidth to be able to debug your DWR setup issues. Either through Java Annotations or in your dwr.xml file you need to specify that DWRProxySample is a remote proxy with name "DWRProxySampleInterface". You can read about how to do this on DWR's website. The error "DWRProxySampleInterface is not defined" means that DWR isn't generating DWRProxySampleInterface.js or your aren't including it in your HTML file.

loeppky
8 Feb 2008, 9:55 AM
djiao: although I haven't forgotten about it, I haven't gotten to the grid example yet. I have had other things come up at work that I've needed to attend to first. Once I am able to continue development on our JavaScript project, I will finish off the example, as I need it for myself as well.

djiao
8 Feb 2008, 11:05 AM
So glad that I figured it out myself how to use this DWRProxy for grid! Thank loeppky so much for putting the proxy together! It works great!

Below is my code:

JavaScript



var reader = new Ext.data.JsonReader({
totalProperty: "totalSize",
root: "data"
}, Ext.data.Record.create([{
name: "identifier",
type: "string"
}, {
name: "title",
type: "string"
}, {
name: "creator",
type: "string"
}]));

var store = new Ext.data.Store({
proxy: new Ext.ux.data.DWRProxy({
dwrFunction: RepositoryManager.list,
listeners: {
'beforeload': function(dataProxy, params){
params[dataProxy.loadArgsKey] = ['query'];
}
}
}),
reader: reader
});

var columns = [{
"header": "ID",
"dataIndex": "identifier",
"sortable": "true",
"id": "identifier"
}, {
"header": "Title",
"dataIndex": "title",
"sortable": "true",
"id": "title"
}, {
"header": "Creator",
"dataIndex": "creator",
"sortable": "true",
"id": "creator"
}];

// create the Grid
var grid = new Ext.grid.GridPanel({
store: store,
columns: columns,
stripeRows: true,
height: 200,
title: 'DWRProxy Grid',
});
store.load();
grid.render('grid-example');
grid.getSelectionModel().selectFirstRow();


Java:


@RemoteProxy
public class RepositoryManager {
...

@RemoteMethod
public Map list(String repoId) throws RepositoryException {
List<Map<String, String>> list = new ArrayList<Map<String, String>>();

Map<String, String> row;

row = new HashMap<String, String>();
row.put("identifier", "COm1");
row.put("title", "asdfasfde");
row.put("creator", "adfa");
list.add(row);

row = new HashMap<String, String>();
row.put("identifier", "COm2");
row.put("title", "asdfasfde");
row.put("creator", "adfa");
list.add(row);

row = new HashMap<String, String>();
row.put("identifier", "COm3");
row.put("title", "asdfasfde");
row.put("creator", "adfa");
list.add(row);

HashMap map = new HashMap();
map.put("totalSize", 3);
map.put("data", list);

String str = JSONSerializer.toJSON(map).toString();
System.out.println(str);
return map;
}
...
}

loeppky
8 Feb 2008, 1:13 PM
djiao: Good stuff. I'm glad to see that it's working for you. I will try out your grid example as soon as I can.

thiagoaos
9 Feb 2008, 7:54 AM
The example use DWR, Spring, Java, ExtJS, loeppky's DWRProxy (don't worry, is a very small modification)
- Hibernate and Mysql ( this is in other layer and i don't show, but i talk about)

Features
Remeber. Paginate, Filter and Sort are done in Server Side.

carExample.jsp




... ext and others js e css imports

<script type="text/javascript" src="dwr/interface/Car.js"></script>
<script type='text/javascript' src='/${pageContext.servletContext.servletContextName}/carExample.js'></script>

<label for="car_description">Description: </label>
<input id="car_description" size="40"/>
<input type="submit" value="Search" onclick="store.load( storeParams );" />

<br />

<div id="car"></div>



carExample.js




var defaultPageSize = 4;
var store;
var storeParams = { params: { start: 0 } };

Ext.onReady(function(){

// create the Data Store
store = new Ext.data.Store({
// load using script tags for cross domain, if the data in on the same domain as
// this page, an HttpProxy would be better
proxy: new Ext.ux.data.DWRProxy({
dwrFunction: Car.getGridData, /* i create a interface with this method and all class that has the method that will invoke dinamic will implement this interface */
listeners: {
'beforeload': function(dataProxy, params) {
params["size"] = defaultPageSize;
params["filter"] = { };

// who don't know this $j is jquery
if( $j("#car_description").get(0) != null && jQuery.trim( $j("#car_description").val() ) != "" )
params["filter"].description = $j("#car_description").val();
}
}
}),

// create reader that reads the Topic records
reader: new Ext.data.JsonReader({
root: 'obj',
id: 'id',
totalProperty: 'size',
fields: [
{name: 'id'},
{name: 'description'},
{name: 'manufacturer.description'} /*I use like this way, because i use hibernate to order by, and inside a car has a manufacturer object with description attr, then i send to server side the name like i will use.*/
]
}),

// turn on remote sorting
remoteSort: true
});
store.setDefaultSort('description', 'asc');

// the column model has information about grid columns
// dataIndex maps the column to the specific data field in
// the data store
var cm = new Ext.grid.ColumnModel([{
header: "ID",
dataIndex: 'id',
width: 50
},{
header: "Description",
dataIndex: 'description',
width: 350
},{
header: "Manufacturer",
dataIndex: 'manufacturer.description',
width: 350
}]);

// by default columns are sortable
cm.defaultSortable = true;

var grid = new Ext.grid.GridPanel({
el:'gridCar',
width:754,
height:300,
title:'Cars',
store: store,
cm: cm,
trackMouseOver:false,
sm: new Ext.grid.RowSelectionModel({selectRow:Ext.emptyFn}),
loadMask: true,
bbar: new Ext.PagingToolbar({
pageSize: defaultPageSize,
store: store,
displayInfo: true,
displayMsg: 'Displaying topics {0} - {1} of {2}',
emptyMsg: "No topics to display",
})
});

// render it
grid.render();

// trigger the data store load
store.load(storeParams);
});



loeppky's DWRProxy modification

i only change the function load like you can see




load : function(params, reader, loadCallback, scope, arg) {
var dataProxy = this;
if (dataProxy.fireEvent("beforeload", dataProxy, params) !== false) {

// I don't need that if here, because i create a object that receive a map to the params, pageSize, start register, attrSort and sortType.
var dwrFunctionArgs = []
dwrFunctionArgs.push(params);

dwrFunctionArgs.push({
callback: function(response){
// call readRecords verses read because read will attempt to evaled the JSON,
// but as this point DWR has already evaled the JSON.
var records = reader.readRecords(response);
dataProxy.fireEvent("load", dataProxy, response, loadCallback);
loadCallback.call(scope, records, arg, true);
},
exceptionHandler: function(message){
dataProxy.fireEvent("loadexception", dataProxy, response, loadCallback, e);
loadCallback.call(scope, null, arg, false);
}
});

this.dwrFunction.apply(Object, dwrFunctionArgs); // the scope for calling the dwrFunction doesn't matter, so we simply set it to Object.
} else { // the beforeload event was vetoed
callback.call(scope||this, null, arg, false);
}
}



The class that i use to receive objects from DWRProxy
DWRExtReceive.java



public class DWRExtReceive implements Serializable {

private Map<String, String> filter;
private Integer start;
private Integer size;
private String sort; //attrSort
private String dir; //sortType

//constructor, setters and getters
}


The class that i use to return objects to DWRProxy
DWRExtCallBack.java



public class DWRExtCallBack {

private Object obj; /* here i return the object collection to use in the grid or i can return only a object to use in other component */
private boolean error; /* if happend some problem i will setter and will know in client side, but i'm not testing yet */
private String msg; /* if i want send some msg, error or sucess */
private Integer size; //to use in paginate grid to inform the total registers

//constructor, setters and getters
}



The interface that i said before, i use this to i know the method that i will call




public interface Grid {
public DWRExtCallBack getGridData( DWRExtReceive receive );
}



The class that is mapped to access dinamic. The map is done in dwr.xml, and i use spring like creator.

CarFacede.java



public class CarFacade implements Grid {

private CarRN carRn; /*will be inject by spring when it create the instance of carFacade. And inside CarRn has a CarDao, that spring will inject too, this is very good */


public DWRExtCallBack getGridData(DWRExtReceive receive) {
DWRExtCallBack cb = new DWRExtCallBack();
try {
Car car = new Car();

/* remember? the car_description that i have in form and before do ajax request i will put in the params["filter"].description = ... */
car.setDescription( receive.getFilter().get("description") );

//my business logic layer will do the business logic and the dao will do the search
cb.setObj( carRn.pesquisar( car, receive.getStart(), receive.getSize(), receive.getSort(), receive.getDir() ) );
cb.setSize( carRn.count( car ) );
} catch (AmbienteException e) {
cb.setError(true);
cb.setMsg( "Error happened"" );
} catch (Exception e) {
cb.setError(true);
cb.setMsg( "Error happened" );
}
return cb;
}
}


Dwr.xml



<dwr>
<allow>
<create creator="spring" javascript="Car" >
<param name="beanName" value="carFacade"/>
<exclude method="getCarRn"/>
<exclude method="setCarRn"/>
</create>

<convert converter="bean" match="java.lang.Object"/>
<convert converter="bean" match="br.com.example.model.*"/>
<convert converter="bean" match="br.com.example.util.*"/>
</allow>
</dwr>


applicationContext of the Spring



<beans default-autowire="autodetect">

<bean id="carDao" class="br.com.example.dao.CarDAO"/>
<bean id="carRn" class="br.com.example.business.CarRN"/>
<bean id="carFacade" class="br.com.example.ajaxfacade.CarFacade" name="carFacade"/>

</beans>


Maybe if i have time i will do the example and put the source here. This example is of one project that i am doing, brazilian project, and before i post here i change the names to english and other names. But the example works fine.

Any doubt, do the question.

Thanks loeppky to DWRProxy, very good extension.

loeppky
11 Feb 2008, 10:11 AM
thiagoaos,

I'm glad to hear things are working for you. A couple of comments:

Stylistically, this "beforeload" handler:


'beforeload': function(dataProxy, params) {
params["size"] = defaultPageSize;
params["filter"] = { };
if( $j("#car_description").get(0) != null && jQuery.trim($j("#car_description").val() ) != "" )
params["filter"].description = $j("#car_description").val();
}

could be better written as:


'beforeload': function(dataProxy, params) {
params.size = defaultPageSize;
params.filter = { };
if( $j("#car_description").get(0) != null && jQuery.trim($j("#car_description").val() ) != "" )
params.filter.description = $j("#car_description").val();
}

You were missing "bracket" and "dot" property accessing unnecessarily. I think it is most clear to use "bracket" notation when the key is a variable, not an already known string.
While there are certainly some niceties in defining a "DWRExtReceive" class, it isn't very Java like. If you ever wanted to call your DWR interface methods from another Java class, it would be very silly to have to create a "DWRExtReceive" object to hold the parameters. If I were you, I would do the following:


public interface Grid {
public DWRExtCallBack getGridData(Map<String, String> filter, int start, int size, int sort, String dir);
}



'beforeload': function(dataProxy, params) {
var filter = {};
if( $j("#car_description").get(0) != null && jQuery.trim($j("#car_description").val() ) != "" ) {
filter.description = $j("#car_description").val();
}
var loadArgs = [filter, params.start, defaultPageSize, params.sort, params.dir];
params[dataProxy.loadArgsKey] = loadArgs;
}

This change would require to use the DWRProxy that I originally posted which is more generic, than your stripped down version.


I hope that makes sense. Let me know if you have any questions.

thiagoaos
11 Feb 2008, 2:21 PM
params.filter.description = $j("#car_description").val();



thx, i changed this later but i don't change in my post.



var loadArgs = [filter, params.start, defaultPageSize, params.sort, params.dir];
params[dataProxy.loadArgsKey] = loadArgs;


This don't work to me.
If i do this and change back to originally dwrproxy happened error because my param in java method don't receive any value

public DWRExtCallBack getGridData(DWRExtReceive receive) {
all receive attr is null, because was sent i array value and don't a object.
}

i put a alert like below to see how the param is send to remote method in java.
And the result you can see more below.



alert(DWRUtil.toDescriptiveString(dwrFunctionArgs,2));
this.dwrFunction.apply(Object, dwrFunctionArgs);





[
{},
0,
4,
"descricao",
"ASC"
]

with my modification is sent a object like this.


{
filter: { description: "test" }, sort: "descricao", dir: "ASC", size: 4, start: 0
}

and dwr marshal very fine to my a instance of the DWRExtReceive object.

Sent a array i can't get in java by a name, i will get by a index, whatever, start is index 1 of the array, sort is index "3" of the array. This is good and not good. Good because a can pass any param without modifier a receive class, but i can put a attribute in a generic receive class to receive a object map, and i will can receive any param too.

I like do a object to work with interfaces and components, because the other users will know exactly what their have to do. Freedom to programmer user is not very good.

But i can change the dwrproxy to work in two way.

I am doing a very good example to avaliable in this forum.

thanks again for dwrproxy and the tips.

Sorry for my bad english.

loeppky
11 Feb 2008, 3:29 PM
thiagoaos,

In order to use


var loadArgs = [filter, params.start, defaultPageSize, params.sort, params.dir];
params[dataProxy.loadArgsKey] = loadArgs;

with the original DWRProxy I posted, you must also use the Java method I pasted:


public interface Grid {
public DWRExtCallBack getGridData(Map<String, String> filter, int start, int size, int sort, String dir);
}


That said, if you still want to use your original getGridData method that takes an DWRExtReceive object, that is fine. You can do so though using my original DWRProxy class. Here's how you'd do it:


'beforeload': function(dataProxy, params) {
var filter = {};
if( $j("#car_description").get(0) != null && jQuery.trim($j("#car_description").val() ) != "" ) {
filter.description = $j("#car_description").val();
}
var loadArgs = [{
filter,
params.start,
defaultPageSize,
params.sort,
params.dir
}];
params[dataProxy.loadArgsKey] = loadArgs;
}


My implementation of DWRProxy is more generic. It can support your use case. Your simplified version doesn't support a case where the DWR interface method is expecting multiple parameters. Thus to maximize the amount of people who can benefit from the example you are working up, I would encourage you to use my original DWRProxy.

Let me know if this isn't making sense or if you have any questions!

thiagoaos
11 Feb 2008, 5:53 PM
Ok, i understand now.
I was mind.

thx loeppky more one time.

thiagoaos
12 Feb 2008, 8:44 AM
//i use this to generate the form fields to filter the query.
var modeloFilter = [
{ idField: "modelo_descricao", keyName: "descricao", type: "text"},
{ idField: "modelo_marca_descricao", keyName: "marca", type: "text"} ]

var filter = {};

jQuery.each( modeloFilter, function() {
if( jQuery("#" + this.idField).get(0) != null && jQuery.trim( jQuery("#" + this.idField).val() ) != "" )
eval('filter.' + this.keyName + '= jQuery("#" + this.idField).val()');
});

var loadArgs = [{
'filter': filter,
'start': params.start,
'size': defaultPageSize,
'sort': params.sort,
'dir': params.dir
}];
params[dataProxy.loadArgsKey] = loadArgs;


this works veryl well, thx
I prefer user the object DWRExtReceive because if i want to pass a new value to java method i don't need to change the method signature. Then i use originally DWRProxy posted by you and the code above.

thx

rams
13 Feb 2008, 3:25 PM
Hi,

I am new to extjs.
After integrating your code, I am able to call the java service. But after getting the response
when converting, I am getting the following error.
f.convert is not a function.
in ext-debug-all.js

Can you please help me out.

Thanks

loeppky
13 Feb 2008, 3:44 PM
Rams: you'll have to explain more of what you're doing to receive any help. Did you get the example that I posted to work? If not, start with that. Once you've got that, post any modifications (within CODE tags) so we can see where you may have screwed up.

rams
13 Feb 2008, 4:25 PM
Its just a test page calling a service method for building the grid
code:


var GridUI = function() {
var ds;
var grid; //component
var columnModel; // definition of the columns

function initDataSource() {
var reader = new Ext.data.JsonReader({
totalProperty: "totalSize",
root : "data"
},Ext.data.Record.create([
{name: "id", type: "int"},
{name: "description",type: "String"},
{name: "first",type: "String"},
{name: "last",type: "String"}

]));



ds = new Ext.data.Store({
proxy: new Ext.ux.data.DWRProxy({
dwrFunction: TestService.getItems,
listeners: {
'beforeload' : function(dataProxy, params){
params[dataProxy.loadArgsKey] = ['Test',true,1,10,'Asc'];
}
}
}),

reader:reader
});

ds.load();
}

function getColumnModel() {
if(!columnModel) {
columnModel = new Ext.grid.ColumnModel(
[
{
header: 'Description',
width: 250,
sortable: true,
dataIndex: 'description',
},
{
header: 'First Name',
width: 250,
sortable: true,
dataIndex: 'first',
},
{
header: 'Last Name',
width: 250,
sortable: true,
dataIndex: 'last',
}
]
);
}
return columnModel;
}

function buildGrid()
{
var sm = new Ext.grid.CheckboxSelectionModel();
grid = new Ext.grid.GridPanel({
el:'remove-zip', // HTML #id to render to
//title:'Remove Zip codes',
//height:135, /* 4 rows (21px/ea) = 84px + { grid header(24px) + border(2px) + title(25px) } = 51px */
height:110, /* 4 rows (21px/ea) = 84px + { grid header(24px) + border(2px) + toolbar(26px) } = 52px */
loadMask: true,
enableHdMenu:false, // no need for a grid header drop-down menu

ds: ds,
sm: sm,
cm: new Ext.grid.ColumnModel([
sm,
{header: "ID", width: 60, sortable: true, dataIndex: 'id'},
{header: "description", width: 120, sortable: true, dataIndex: 'description'},
{header: "First", width: 50, sortable: true, dataIndex: 'first'},
{header: "Last", width: 60, sortable: true, dataIndex: 'last'}
]),

// inline top toolbar
tbar:[{
id:'remove-btn',
text:'Remove selected',
tooltip:'Remove the selected zip code(s)',
iconCls:'icon-remove',
//disabled: true, //disable until 1 or more rows selected
handler: function(){
Ext.MessageBox.confirm('Confirm', 'Are you sure that you want to remove the selected zip code(s)?');
}
}],
viewConfig: {
forceFit:true
}
});

}

return {
init : function() {
initDataSource();
ds.load({params:{start:0, limit:22}, arg:['walter', true]});
buildGrid();
},

getStore: function() {
return ds;
}
}
}();




Ext.onReady(GridUI.init, GridUI, true);
</code>

<code>
<%@ include file="../taglibs.jsp"%>
<div id="content">

<div id="myDiv">This is a test div.</div>

<input type="button" id="myButton" value="My Button" onclick="onClickTest()"/>

<div id="mygrid" style="border:1px solid #99bbe8;overflow: hidden; height: 300px;"></div>

</div>
</code>

<code>





public class TestService {


public ListRange getItems(String name, boolean flag, int start, int count, String orderBy) {
System.out.println("start=" + start + ";count=" + count + ";name=" + name + ";flag=" + flag);
ListRange listRange = new ListRange();

Object[] data = {new ToDoItem(1,"item1",new Author("Scott", "Walter")),new ToDoItem(2,"item2",new Author("Scott", "Walter")),new ToDoItem(3,"item3",new Author("Scott", "Walter")),new ToDoItem(4,"item4",new Author("Scott", "Walter")),new ToDoItem(5,"item5",new Author("Scott", "Walter"))};
listRange.setData(data);
listRange.setTotalSize(5555);

return listRange;

}

}

[/QUOTE]

kouphax
17 Feb 2008, 11:07 AM
Hi all,

Excellent extension but I have one problem and I apologise if it's been addressed before. The exception handler...


exceptionHandler: function(message){
dataProxy.fireEvent("loadexception", dataProxy, response, loadCallback, e);
loadCallback.call(scope, null, arg, false);
}


Where are the variables response and e being declared? The code falls over for me when an exception is thrown. I recall changing the original code for myself to


dataProxy.fireEvent("loadexception", dataProxy, message, loadCallback, null);

But it seems this was never addressed by anyone else and I wonder if I am forgetting something.

Is this a bug or an oversight on my part?

James.

bowa
18 Feb 2008, 6:59 AM
I am a little confused. in ext 1.x i used an ObjectReader together with DWRProxy, now in the threads about DWRProxy in ext2.0 all i see are MapReaders, ArrayReaders and JSONReaders ... while DWR returns plain javascript objects.

is there an ObjectReader (DWRReader) class that work ? if i use the ext 1.0 one my comobo box stays on 'loading' without any error, but without any result either.

this is what goes over the wire as a result of my call.


//#DWR-INSERT

//#DWR-REPLY

var s0={};var s1={};var s2={};var s3={};var s4={};s0.addr="address-1";s0.extra="help";s0.id=1;

s1.addr="address-2";s1.extra="help";s1.id=2;

s2.addr="address-3";s2.extra="help";s2.id=3;

s3.addr="address-4";s3.extra="help";s3.id=4;

s4.addr="address-5";s4.extra="help";s4.id=5;

dwr.engine._remoteHandleCallback('0','0',[s0,s1,s2,s3,s4]);

a List of Objects, so translated its an array of javascript objects.

this is my code but it stays on 'loading'



var store = new Ext.data.SimpleStore({
proxy: new Ext.ux.data.DWRProxy({
dwrFunction: ShipmentHelper.getAddresses
}),
reader: new Ext.data.ObjectReader(
{id:'id'}, [
{name:'addr'},
{name:'extra'}
]),
fields: [
{name:'id'},
{name:'addr'},
{name:'extra'}
]
});

var combo = new Ext.form.ComboBox({
store: store,
displayField:'addr',
typeAhead: true,
triggerAction: 'all',
emptyText:'Select an address...',
selectOnFocus:true,
applyTo: 'shipment-0-addresses'
});


the fields property of the SimpleStore also confuses me a bit, when i dont add a fields property i get errors ... i though that a 'proxy' and a 'reader' were enough ?

thanks for your ideas.

loeppky
21 Feb 2008, 1:29 PM
rams: sorry for the delayed response. I have been out of town. Are you still having issues? If so, are they the same ones you reported earlier?

loeppky
21 Feb 2008, 1:45 PM
kouphax: thanks for catching this bug. I copied it forward from Axel's original post. Anyways, I would actually do the following:


exceptionHandler: function(message, exception) {
// the event is supposed to pass the response, but since DWR doesn't provide that to us, we pass the message.
dataProxy.fireEvent("loadexception", dataProxy, message, loadCallback, exception);
loadCallback.call(scope, null, arg, false);
}


I have corrected the my original post (http://extjs.com/forum/showthread.php?p=113081#post113081) to include this updated code. Thanks again for catching this!

loeppky
21 Feb 2008, 1:50 PM
bowa: use an Ext.data.JsonReader. As commented in the code for in the callback function, Ext.ux.data.DWRProxy "calls readRecords verses read because read will attempt to eval the JSON, but as this point DWR has already evaled the JSON." Let us know how that works for you.

bowa
21 Feb 2008, 11:14 PM
i tried a lot of different ObjectReader classes that are on these forums. But only the following one really does what i want. Map javascript objects to Records directly.



/**
* @class Ext.data.ObjectReader
* @extends Ext.data.DataReader
* Data reader class to create an Array of {@link Ext.data.Record} objects from an array of objects
* based on mappings in a provided Ext.data.Record constructor.<br><br>
* <p>
* Example code:
* <pre><code>
var RecordDef = Ext.data.Record.create([
{name: 'name', mapping: 'name'}, // "mapping" property not needed if it's the same as "name"
{name: 'occupation'} // This field will use "occupation" as the mapping.
]);
var myReader = new Ext.data.ObjectReader({
id: "id" // The field that provides an ID for the record (optional)
}, RecordDef);
</code></pre>
* <p>
* This would consume data like this:
* <pre><code>
[ {id:1, name:'Bill', occupation:'Gardener'}, {id:2, name:'Ben', occupation:'Horticulturalist'} ]
</code></pre>
* @cfg {String} id (optional) The field that provides an ID for the record
* @constructor
* Create a new ObjectReader
* @param {Object} meta Metadata configuration options.
* @param {Mixed} recordType The definition of the data record type to produce. This can be either a
* Record subclass created with {@link Ext.data.Record#create}, or an array of objects with which to call
* Ext.data.Record.create. See the {@link Ext.data.Record} class for more details.
*/
Ext.ux.data.ObjectReader = function(meta, recordType){
meta = meta || {};
Ext.ux.data.ObjectReader.superclass.constructor.call(this, meta, recordType||meta.fields);
};
Ext.extend(Ext.ux.data.ObjectReader, Ext.data.DataReader, {
/**
* This method is only used by a DataProxy which has retrieved data from a remote server.
* <p>
* Data should be provided in the following structure:
* <pre><code>
{
objects : [ { }, { }... ], // An array of objects
totalSize : 1234 // The total number of records (>= objects.length)
}
</code></pre>
* The 'objects' field is required; other fields are optional.
* @param {Array} response An object containing an array of objects and meta data.
* @return {Object} records A data block which is used by an {@link Ext.data.Store} as
* a cache of Ext.data.Records.
* <p>
* Note: This implementation is intended as a convienience to simplify writing DataProxy
* subclasses and to guide implementations into common field names to return result data.
* If these fields are unnatural for a proxy, it may call readRecords() directly and handle
* this functionality itself.
*/
read : function(response){
if( undefined == response.objects ) {
throw {message: "ObjectReader.read: Objects not available"};
}
var result = this.readRecords(response.objects);
if ( undefined != response.totalSize )
result.totalRecords = response.totalSize;
return result;
},

/**
* Create a data block containing Ext.data.Records from an an array of objects.
* @param {Object} objects An array of objects.
* @return {Object} records A data block which is used by an {@link Ext.data.Store} as
* a cache of Ext.data.Records.
*/
readRecords : function(objects){
var records = [];
var recordType = this.recordType, fields = recordType.prototype.fields;
var idField = this.meta.id;
for(var i = 0; i < objects.length; i++) {
var object = objects[i];
var values = {};
for(var j = 0; j < fields.length; j++){
var field = fields.items[j];
var v = object[field.mapping || field.name] || field.defaultValue;
v = field.convert(v);
values[field.name] = v;
}
var id = idField ? object[idField] : undefined;
records[records.length] = new recordType(values, id);
}
return {
records : records,
totalRecords : records.length
};
}
});


it works in both in 1.x and 2.x

loeppky
22 Feb 2008, 9:11 AM
bowa: I don't understand why you need a custom ObjectReader class as compared to using the provided Ext.data.JsonReader. JsonReader reads objects. Can you explain why you need this custom class?

cikcik
25 Feb 2008, 1:53 AM
Hi, thanks for your DWR Proxy.
I'm new in ExtJs & DWR.
I have tried to get data from DWR, it's successful load, buat grid table still empty.

This is my script :


Ext.onReady(function() {

Ext.state.Manager.setProvider(new Ext.state.CookieProvider());

var recordType = Ext.data.Record.create([
{name: "id",mapping:"id"},
{name: "user", mapping:"user"},
{name: "password", mapping: "password"},
{name: "initial",mapping: "initial"},
{name: "email", mapping: "email"},
{name: "name", mapping:"name"},
{name: "access", mapping:"access"},
{name: "active", mapping:"active"},
{name: "createdDate", mapping:"createdDate"},
{name: "lastUpdated", mapping:"lastUpdated"},
{name: "createdBy", mapping:"createdBy"},
{name: "lastUpdatedBy", mapping:"lastUpdatedBy"}
]);

var reader = new Ext.data.JsonReader({
totalProperty: "totalSize",
root: "data",
id: "id"
}, recordType);


var store = new Ext.data.Store({
proxy: new Ext.ux.data.DWRProxy({
dwrFunction: UserUtil.listUser,
listeners: {
'beforeload': function(dataProxy, params) {
params[dataProxy.loadArgsKey] = [''];
}
}
}),
reader: reader
});


// create the Grid
var grid = new Ext.grid.GridPanel({
store: store,
columns: [
{id:'id',header: "ID", width: 30, sortable: true, dataIndex: 'id'},
{id:'name',header: "Name", width: 190, sortable: true, dataIndex: 'name'},
{id:'user',header: "User", width: 80, sortable: true, dataIndex: 'user'}
],
stripeRows: true,
height:350,
title:'User List'
});


store.load();

grid.render('grid-example');

grid.getSelectionModel().selectFirstRow();

});

My java class :


public static List<User> listUser() {
Session session = null;
Transaction tx = null;

try {
session = currentSession();
tx = session.beginTransaction();
List list = session.createQuery("from User").list();
tx.commit();
return list;
} catch (RuntimeException ex) {
if (tx != null) {
tx.rollback();
}
throw ex;
} finally {
UserUtil.closeSession();
}
}

In firebug console :

throw 'allowScriptTagRemoting is false.';

//#DWR-INSERT

//#DWR-REPLY

var s0={};var s1={};var s2={};var s3={};var s4={};var s5={};var s6={};var s7={};var s8={};var s9={};var

s10={};var s11={};var s12={};var s13={};var s14={};s0.access=null;s0.active="Y";s0.createdBy=null;s0

.createdDate=new Date(1154451600000);s0.email="yastri@cku.co.id";s0.id=1;s0.initial="ys";s0.lastUpdated

=new Date(1202522297000);s0.lastUpdatedBy="yastri";s0.name="Suryastri Boni";s0.password="yastri";s0.user

="yastri";

s1.access=null;s1.active="Y";s1.createdBy="yastri";s1.createdDate=new Date(1154451600000);s1.email="ystu

@cku.co.id";s1.id=2;s1.initial="su";s1.lastUpdated=new Date(1154486110000);s1.lastUpdatedBy="yastri"

; ..........................................

s14.access=null;s14.active="Y";s14.createdBy="yastri";s14.createdDate=new Date(1193850000000);s14.email

="";s14.id=15;s14.initial="ad";s14.lastUpdated=new Date(1200015191000);s14.lastUpdatedBy="yastri";s14

.name="Almadoni Doni";s14.password="doni1234";s14.user="doni";

dwr.engine._remoteHandleCallback('0','0',[s0,s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11,s12,s13,s14]);

Could you help me, what is wrong?
I think there's an error in data reader.

Thanks in advance.

loeppky
25 Feb 2008, 11:59 AM
cikcik: This isn't a DWRProxy issue. You actually aren't returning the data in a format that Ext.data.JsonReader is expecting. Your Java code is returning an array of objects. JsonReader is expecting an Object with two properties: totalSize and data. totalSize should have an integer value. data should have an array of objects. As a result, your JavaCode should look like:



public static List<User> listUser() {
Session session = null;
Transaction tx = null;

try {
session = currentSession();
tx = session.beginTransaction();
List data = session.createQuery("from User").list();
tx.commit();
HashMap returnObj = new HashMap();
returnObj.put("data", data);
returnObj.put("totalSize", data.size());
return returnObj;
} catch (RuntimeException ex) {
if (tx != null) {
tx.rollback();
}
throw ex;
} finally {
UserUtil.closeSession();
}
}

cikcik
25 Feb 2008, 6:10 PM
dear loeppky : thanks for your quick response.
I have try to hashmap, still cannot load data object to store :(
and there's a little different in firebug response:
dwr.engine._remoteHandleCallback('0','0',{data:s0,totalSize:15});

loeppky
26 Feb 2008, 9:51 AM
cikcik: your incoming data looks good from what I can tell. The problem may have something else to do with your grid/store configuration. Here are the things I would try:

Try setting a breakpoint within the DWRProxy callback function at the line with "var records = reader.readRecords(response);" Ensure that records are being created correctly.
Compare your example to dijao's (http://extjs.com/forum/showthread.php?p=121536#post121536). He successfully is using DWRProxy, JsonReader, and a grid.
Make sure you can get your grid to display with an Ext.data.SimpleStore.

I hope that works out for you. Let me know how it goes.

purist
26 Feb 2008, 12:06 PM
Dear all,

I try to use DWR and Extjs 2.0

I integrate the script regarding the script from loeppky:


var ds = new Ext.data.Store({
proxy: new Ext.ux.data.DWRProxy({
dwrFunction: agriculteurDWRManager.getAgriculteursByReferences,
listeners: {
'beforeload': function(dataProxy, params){}
}

}
),
reader: new Ext.data.JsonReader(
{totalProperty: 'total', root:'list'},
[{identifiant: 'identifiant'}]
)
});


But I've got the error.
When I use analyse, the value this.dwrFunction is undefined


(firefox debug console message)
Erreur : dataProxy.dwrFunction has no properties
Fichier source : http://localhost:8080/telefda/scripts/extjs/dwr.js
Ligne : 90


Can someone help me ???

cikcik
26 Feb 2008, 6:39 PM
loepkky:
I have tried to set breakpoint or alert, but the script doesn't seem through "var records = reader.readRecords(response);", alert not come or stop at the breakpoint.
I don't know what's wrong :(
when I tried djiao's code, I've successfully load data to store. firebug will stop at breakpoint.

Djiao's code, and successfully load.

public Map list(String repoId){
List<Map<String, String>> list = new ArrayList<Map<String, String>>();

Map<String, String> row;

row = new HashMap<String, String>();
row.put("identifier", "COm1");
row.put("title", "asdfasfde");
row.put("creator", "adfa");
list.add(row);

row = new HashMap<String, String>();
row.put("identifier", "COm2");
row.put("title", "asdfasfde");
row.put("creator", "adfa");
list.add(row);

row = new HashMap<String, String>();
row.put("identifier", "COm3");
row.put("title", "asdfasfde");
row.put("creator", "adfa");
list.add(row);

HashMap map = new HashMap();
map.put("totalSize", 3);
map.put("data", list);
return map;
}

and my data, it's not load the data

public static Map listUsers() {
Session session = null;
Transaction tx = null;

try {
session = currentSession();
tx = session.beginTransaction();
List data = session.createQuery("select id, name, user from User").list();
tx.commit();
HashMap map = new HashMap();
map.put("totalSize", data.size());
map.put("data", data);
return map;
} catch (RuntimeException ex) {
if (tx != null) {
tx.rollback();
}
throw ex;
} finally {
UserUtil.closeSession();
}
}

cikcik
26 Feb 2008, 10:19 PM
loepkky: I have solve the problem.

script cannot read "var records = reader.readRecords(response);" because no parameter di java code and empty parameter in DWRProxy

public static Map listUsers(){}

params[dataProxy.loadArgsKey] = ['']


when I add dummy parameter in Java function & DWRProxy like below this :

public static Map listUsers(String mapid){}

params[dataProxy.loadArgsKey] = ['query']

it's works.

Should I use dummy parameter when I call all my data without parameter?
Thanks again for your support.

loeppky
27 Feb 2008, 9:42 AM
cikcik: here's the issue. With this code:


public static Map listUsers(){}
params[dataProxy.loadArgsKey] = ['']

you're saying that the dwrFunction should be called with one parameter. This parameter is a String, and it's the empty string. Your Java method though is expecting zero arguments. DWR, as a result, doesn't know which method to call.

What you should do instead is:


public static Map listUsers(){}
params[dataProxy.loadArgsKey] = []

At this point, the dwrFunction will be called with no parameters, which is exactly what you want. See if that works for you.

loeppky
27 Feb 2008, 9:46 AM
purist: you are setting the dwrFunction to "agriculteurDWRManager.getAgriculteursByReferences". Are you sure that "agriculteurDWRManager.getAgriculteursByReferences" is defined when the Ext.ux.data.DWRProxy is instantiated? Set a breakpoint in Firebug at the line where you instantiate the DWRProxy and make sure "agriculteurDWRManager.getAgriculteursByReferences" is defined.

cikcik
27 Feb 2008, 5:59 PM
it's works....
thanks loeppky...the problem has solved :-)

cikcik
28 Feb 2008, 11:21 PM
Dear loeppky,
after solve load data to grid, I have a problem with paging.
all data always show.
I just want to show 10 data per page.

Should I use, set size data when query from java?
Or can I call all data and dwrproxy will do the paging size?

Could you help me? Thanks in advance



bbar: new Ext.PagingToolbar({
pageSize: 10,
store: store,
displayInfo: true,
displayMsg: 'Displaying users {0} - {1} of {2}',
emptyMsg: "No users to display"
}),

loeppky
29 Feb 2008, 12:37 PM
cikcik:all the paging toolbar is set parameters that are passed to the proxy during the load method. There are three things you must do:

Make sure your DWR method in Java expects the "paging" parameters and handles them correctly.
Make sure that the object returned by DWR has the has your totalProperty (totalSize), where totalSize is the the number of records that would be returned without paging.
Make sure you are passing the "paging" parameters to the server. You will do this in your "beforeload" listener. Before you were doing:

params[dataProxy.loadArgsKey] = []
Now you will need to actually set values in that array as compared to leaving it empty. You can get the "paging" parameters from the the params object that is provided to the "beforeload" listener. For example:

params[dataProxy.loadArgsKey] = [params.start, params.limit]

I hope this makes sense. Good luck!

parmar
3 Mar 2008, 4:09 AM
Hi,

I ma following the tutorial as above and found the same issue as below. Except i can generate the DWRProxySampleInterface as can be seen on http://localhost:9080/rs/dwr/test/DWRProxySampleInterface.

When i execute http://localhost:9080/rs/ext/DWRPRoxy.html in firebug i get

DWRProxySampleInterface is not defined
(no name)()DWRPRoxy.html (line 34)
fire()ext-all-debug.js (line 1504)
fireDocReady()ext-all-debug.js (line 1541)
[Break on this error] dwrFunction: DWRProxySampleInterface.getPossibleBusinessGroups,

Please could you help:

I am using annotations.



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="../ext-2.0.1/resources/css/ext-all.css"/>

<!-- Ext dependencies -->
<script type="text/javascript" src="../ext-2.0.1/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="../ext-2.0.1/ext-all-debug.js"></script>

<!-- Ext extension dependencies -->
<script type="text/javascript" src="../ext-extensions/DWRProxy.js"></script>

<!-- DWR dependencies -->
<script type='text/javascript' src='/rs/dwr/interface/DWRProxySampleInterface.js'></script>
<script type='text/javascript' src='/rs/dwr/engine.js'></script>
<script type='text/javascript' src='/rs/dwr/util.js'></script>

<script type="text/javascript">
Ext.onReady(function(){
var viewport = new Ext.Viewport({
items: [{
xtype: 'form',
border: false,
labelAlign: 'left',
labelWidth: 100,
defaults: {
width: 230
},
items: [{
xtype: 'combo',
fieldLabel: 'Business Group',
name: 'businessGroup',
store: new Ext.data.Store({
proxy: new Ext.ux.data.DWRProxy({
dwrFunction: DWRProxySampleInterface.getPossibleBusinessGroups,
listeners: {
'beforeload': function(dataProxy, params){
// setting the args that will get passed to the DWR function
params[dataProxy.loadArgsKey] = ['loeppkyIsMyUserId', params.query];
}
}
}),
reader: new Ext.data.ArrayReader({}, Ext.data.Record.create([{
name: 'businessGroupName'
}]))
}),
displayField: 'businessGroupName',
queryParam: 'query',
value: 'Default Value'
}]
}]
});
});
</script>
</head>
<body>

lkjoi
</body>
</html>







/*
* DWRPRoxySample.java


package xxxxxxxxxx;

import java.util.ArrayList;
import java.util.List;

import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;

@RemoteProxy(name="DWRProxySampleInterface")
public class DWRPRoxySample {

@RemoteMethod
public static List<List<String>> getPossibleBusinessGroups(String userId, String query) {

List<List<String>> groupNames = new ArrayList<List<String>>();
List<String> groupName;

groupName = new ArrayList<String>();
groupName.add("group1");
groupNames.add(groupName);

groupName = new ArrayList<String>();
groupName.add("group2");
groupNames.add(groupName);

groupName = new ArrayList<String>();
groupName.add("group3");
groupNames.add(groupName);

return groupNames;
}
}






ka3S: since the name of the Java class is "DWRProxySample", you should name the file "DWRProxySample.java". Also, I don't have the bandwidth to be able to debug your DWR setup issues. Either through Java Annotations or in your dwr.xml file you need to specify that DWRProxySample is a remote proxy with name "DWRProxySampleInterface". You can read about how to do this on DWR's website. The error "DWRProxySampleInterface is not defined" means that DWR isn't generating DWRProxySampleInterface.js or your aren't including it in your HTML file.

parmar
3 Mar 2008, 4:14 AM
this is excellent thanks for the tutorial!!

parmar
3 Mar 2008, 6:10 AM
Hi,

I am returning a List<Row<Object>> from a DWRProxy call. I can see in my debugger the object being passed.

When i alert the object in my javascript all i get is a list of commas. 14 in fact which is the total no of rows i am returning.

I can also see in my console?

DefaultConverterManager - No converter found for com.company.projname.webapp.grid.Grid$Row'



ActivitySearchDataInterface.getGridData(parameters, handleGridData)
function handleGridData(grid) {
alert(grid);
}



Can someone help please what do i need to do? Am hoping to return this data into the JSONReader to populate my grid?

parmar
3 Mar 2008, 7:08 AM
I have added this to dwr.xml



<dwr>
<allow>
<convert converter="collection" match="com.company.myproj.webapp.grid.Grid$Row"/>
<create creator="new" javascript="ActivitySearchData">
<param name="class" value="com.company.myproj.webapp.module.search.activity.ActivitySearchData" />
</create>
<create creator="new" javascript="Functions">
<param name="class" value="com.company.myproj.webapp.functions.Functions" />
</create>

</allow>
</dwr>



but i get the same result?

parmar
3 Mar 2008, 7:29 AM
please can someone help?

loeppky
3 Mar 2008, 9:12 AM
parmar: a couple of things you should do for debugging this on your own:

Set a breakpoint in Java code and ensure that the data being returned looks good. Insert a breakpoint at the return statement.
Set a breakpoint within DWRProxy to look at the response that has been received. Specifically, I would insert a breakpoint at this line: "var records = reader.readRecords(response);"

parmar
3 Mar 2008, 12:46 PM
hi,

i can see the object in th java debugger as a List<Row<Object>> object. I just wanted to get the toString() value of the object in my javascript to prove there was data. If so my next step was to loop iterate the object and make it JSON compliant and return String.

I have not tried point 2.

On executing by dwr call i get this message in my condole:

DefaultConverterManager - No converter found for com.company.projname.webapp.grid.Grid$Row'

I dont know how to convert this class. Its a nested class of return type List.

I am a newbie on ext and dwr.

Not really sure what the issue is but looks like dwr converter issue.
ill try point 2.

loeppky
3 Mar 2008, 1:08 PM
parmar: it does look like a DWR converter issue. That said, it would be best to keep this thread's posts related to issues/questions with DWRProxy, not DWR itself. There are undoubtedly better forms online for that. Good luck on getting DWR to work, and feel free to post if you have any DWRProxy specific issues.

parmar
3 Mar 2008, 1:36 PM
so should i only be returning a String in JSON form, is this the best practice?

shane.fox
3 Mar 2008, 11:45 PM
parmar: Do you have the class 'com.company.projname.webapp.grid.Grid$Row' listed in web.xml /dwr.xml?

parmar
4 Mar 2008, 2:31 AM
yes,



<convert converter="collection" match="com.company.projname.webapp.grid.Grid$Row"/>
<create creator="new" javascript="ActivitySearchData">
<param name="class" value="com.company.projname.webapp.module.search.activity.ActivitySearchData" />
</create>



and in...dwr.xml



<init-param>
<param-name>classes</param-name>
<param-value>
com.company.projname.webapp.dwr.DWRPRoxySample,
com.company.projname.webapp.module.search.activity.ActivitySearchData
</param-value>
</init-param>


Any help/direction would be appreciated. In the meantime i am going to return a Map of objects and use A JSONSerialiser.

shane.fox
4 Mar 2008, 8:06 PM
parmar: Is com.company.projname.webapp.grid.Grid$Row really a collection? if it doesn't implement java.util.Collection then try changing the converter to 'bean'.

Another thing to try is adding com.company.projname.webapp.grid.Grid$Row to web.xml. (I had to do this, but I am using annotations).

parmar
5 Mar 2008, 11:50 AM
shane thanks for your help this worked.

parmar
6 Mar 2008, 2:47 AM
Hi,

When i load my page i call DWR to populate my data. As in the example below.
I need to implement a button that will make a DWR call to another MyCLass.method request with new data to populate the grid.

Using the example below how could this be achieved:




Ext.onReady(function() {

var reader = new Ext.data.JsonReader({
totalProperty: "totalSize",
root: "data"
}, Ext.data.Record.create([{
name: "identifier",
type: "string"
}, {
name: "title",
type: "string"
}, {
name: "creator",
type: "string"
}]));

var store = new Ext.data.Store({
proxy: new Ext.ux.data.DWRProxy({
dwrFunction: RepositoryManagerInterface.list,
listeners: {
'beforeload': function(dataProxy, params){
params[dataProxy.loadArgsKey] = ['query'];
}
}
}),
reader: reader
});

var columns = [{
"header": "ID",
"dataIndex": "identifier",
"sortable": "true",
"id": "identifier"
}, {
"header": "Title",
"dataIndex": "title",
"sortable": "true",
"id": "title"
}, {
"header": "Creator",
"dataIndex": "creator",
"sortable": "true",
"id": "creator"
}];

// create the Grid
var grid = new Ext.grid.GridPanel({
store: store,
columns: columns,

tbar:[{
text:'export',
handler: export
}
store.load();
c grid.render('grid-example');
grid.getSelectionModel().selectFirstRow();


});



So effectively what i am trying to achieve is to dynamically change the dwrfunction call with any DWR request without creating a new a datastore based on the parameter passed by clicking the export button for example. I need to do this for several buttons, but i dont want to keep creating new datastores for each action.

How can i make this generic, any direction would be helpful.

To reload data, do i refresh the store or the grid.

ANy help or direction would be appreciated.

parmar
6 Mar 2008, 6:11 AM
ok,

I have got a bit closer to a solution. I am calling a script function on click of my button.



re
function nextPage(){
gridAction = "MyClass.method"; //new method
store.load();
}



re setting gridAction varaible:




var gridAction = MyClass.method;//old method



but:




var dwrProxy = new Ext.ux.data.DWRProxy({
dwrFunction: gridAction,
listeners: {
'beforeload': function(dataProxy, params){
params[dataProxy.loadArgsKey] = [parameters];
}
}
});



gridAction is still calling my oldMethod and passing data. It is not chnaging my dwrFunction value?

Could anyone assist?

loeppky
6 Mar 2008, 9:05 AM
parmar: dwrFunction is a property of the DWRProxy class. You change this property like you would any other property in JavaScript. If dwrProxy is the name of your Ext.ux.data.DWRProxy instance, then you do dwrProxy.dwrFunction = MyClass.method.

parmar
6 Mar 2008, 9:13 AM
thank you.....


listeners: {
'beforeload': function(dataProxy, params){
if(gridAction == "next"){
dataProxy.dwrFunction = class.method
}
else{
dataProxy.dwrFunction = class2.method2;
}
params[dataProxy.loadArgsKey] = [parameters];
}

parmar
12 Mar 2008, 2:32 AM
Hi,

My call to Class.method throws an exceptionon the server side, how can i trap this response in Ext.

I have tried all the listeners for grid, proxy etc on this thread:

http://extjs.com/forum/showthread.php?t=27784

but i dont get anything alerted. All i see is my loadmask icon being loaded status.

I can see in firebug the following stack trace.

response is not defined
exceptionHandler("Error", Object javaClassName=java.lang.Throwable message=Error)DWRProxy.js (line 88)
_remoteHandleException("1", "0", Object javaClassName=java.lang.Throwable message=Error)engine.js (line 920)
_eval("\r\n//#DWR-INSERT\r\n//#DWR-REPLY\r\ndwr.engine._remoteHandleException('1','0',{javaClassName:"java.lang.T...")engine.js (line 970)
_stateChange(Object map=Object charsProcessed=0 paramCount=0)engine.js (line 859)
onreadystatechange()engine.js (line 642)
[Break on this error] dataProxy.fireEvent("loadexception", dataProxy, response, loadCallback, exc...

I need to catch this is EXT as an error so i can do something else?

Please can someone advise?

deepakjacob
12 Mar 2008, 6:50 AM
As per the below example 'DWRProxySampleInterface.getPossibleBusinessGroups' registers itself with window object. Then


proxy: new Ext.ux.data.DWRProxy({
dwrFunction: DWRProxySampleInterface.getPossibleBusinessGroups,'
should be
proxy: new Ext.ux.data.DWRProxy({
dwrFunction: this.DWRProxySampleInterface.getPossibleBusinessGroups, . Am I right ?




[QUOTE=loeppky;113082]Here

loeppky
12 Mar 2008, 9:23 AM
parmar: although I changed it on my local copy and wrote about it in post #44 (http://extjs.com/forum/showthread.php?p=127271#post127271), I forgot to paste the fix back to the original post. Anyways, you should use the exceptionHandler as defined in the first post for DWRPrxoy (http://extjs.com/forum/showthread.php?t=23884). You can then listen to the "loadexception" event for the proxy. Let me know how that works.

loeppky
12 Mar 2008, 9:31 AM
deepakjacob: 2 things:

It's best to only quote the portion of a previous post that pertains directly to your post so that the thread stays as readable as possible.
You should do some reading on the "this" keyword in JavaScript. "this" refers to the object on which a call is made. As a result, it is most likely not correct to do this.DWRProxySampleInterface.getPossibleBusinessGroups. You are correct in saying that DWRProxySampleInterface is a global variable that belongs to the window. If you want to be clear, you could do window.DWRProxySampleInterface.getPossibleBusinessGroups. this.DWRProxySampleInterface.getPossibleBusinessGroups would only make sense if it's the window instantiating the Ext.ux.data.DWRProxy. I haven't ever seen that case before though, thus would just go with DWRProxySampleInterface.getPossibleBusinessGroups.

SeaSharp2
12 Mar 2008, 11:48 AM
Loeppky, Did you manage to find some time to upload a complete client/server working example?

I ask because this was mentioned at the start of the thread but I did not spot anything. Could be I missed something because this thread is getting long with lots of code examples from others.

loeppky
12 Mar 2008, 12:25 PM
SeaSharp2: the second post (http://extjs.com/forum/showthread.php?p=113082#post113082) is a complete sample. Have you tried using it?

I do not have easy access to a public web server with DWR installed that I can demonstrate this if that's what you're asking. If you have DWR installed, you should be able to easily test it out though by copying and pasting the sample code.

krazy
12 Mar 2008, 6:24 PM
thanks for your help,loeppy.
now i can load data from service.
but when i post data to service,
concole will throws exception: org.directwebremoting.extend.MarshallException: Error
marshalling

and my js code like that


recordType = Ext.data.Record.create([
{name: "userId", type: "int"},
{name: "userName", type: "string"},
{name: "passWord", type: "string"},
{name: "email", type: "string"}
]);
var sm=Ext.grid.CheckboxSelectionModel();

the handler of save like that :


function(){
if(sm1.hasSelection()){
var list=sm.getSelections();
recordData=list[0].data;
userManager.insertUser(recordData, function(data) { });
}
}

thank for your any hints!

deepakjacob
12 Mar 2008, 6:44 PM
hi loeppky,
1) Point noted.
2) this was required as I created a record of type 'X', and at the same time 'X' was the name of my java interface. This was a mistake from my side.

Regards,
DJ

SeaSharp2
13 Mar 2008, 12:30 PM
SeaSharp2: the second post (http://extjs.com/forum/showthread.php?p=113082#post113082) is a complete sample. Have you tried using it?

Not yet but if this is the best code example starting point then that is fine by me.

My current quandary is deciding when to invoke a DWR JS function directly and when to route a request via your DWR proxy. My hunch is:

For any Store/Reader/Proxy situation use your proxy.
For adhoc client/server api calls, use the DWR functions.
So that leaves tree population and forms processing. Hmmm! The leading edge of Web 2.0 is so much fun :)

loeppky
13 Mar 2008, 12:36 PM
krazy: what you're describing sounds like some sort of a configuration or parameter issues. Either you don't have dwr configured to know how to marshal/unmarshal the types you are sending to DWR or you are sending a type to DWR that is other than it's expecting. Either way, this isn't a DWRProxy issue, and should be taken up on a DWR forum.

loeppky
13 Mar 2008, 12:45 PM
SeaSharp2: the second post is definitely the best code example starting point. Concerning when to use DWRProxy, and when to call the DWR generated JavaScript classes directly, your thoughts are mostly correct. Here is what I do:

Anything that uses a store (and thus a proxy), I use DWRProxy.
Submitting or loading a form I just use the DWR JavaScript generated classes. Same goes with trees. I fetch all the tree data and then build up the tree manually. That said, there is a DWRTreeLoader extension out there, but I haven't needed to use it, and thus haven't.

dominicadatia
19 Mar 2008, 1:10 AM
Hello,

I am having some difficulties using DWRProxy. It seems that the callback is never made - when the data is returned from the server (I can see in firebug/websphere debug mode), nothing happens and the load mask waits forever. I have put alerts all over the place in the DWRProxy code but they are never called (after the Java returns)

Any ideas anyone?




var jsonReader = new Ext.data.JsonReader({
root:'dataList'
},
Ext.data.Record.create([
{name: "name", mapping:"displayName",type: "String"},
{name: "senCds", mapping:"senCds", type: "Boolean"}
]));
store = new Ext.data.Store({
reader: jsonReader,
proxy: new Ext.ux.data.DWRProxy({
dwrFunction:analyticsRemote.getReportItems,
listeners: { 'beforeload': function(dataProxy, params){
params[dataProxy.loadArgsKey] = ['loeppkyIsMyUserId', params.query];
},
'load': function() {
alert(1);
},
'loadexception': function() {
alert(2);
}
}
}),
remoteSort: false
});


displayName is the property in java..

And the Java



public Map<String, IndexReportItem[]> getReportItems(String tenor) {

List l = new ArrayList();
IndexReportItem item = new IndexReportItem();
item.setDisplayName("Test Item");
l.add(item);
Map m = new HashMap();
// m.put("dataList", l);
// return m;
m.put("data", (IndexReportItem[])l.toArray(new IndexReportItem[0]));
m.put("totalProperty", l.size());
m.put("success",true);
return m;
}

dominicadatia
19 Mar 2008, 7:18 AM
Now solved, was adding a wrong number of params which meant the callback function was undefined.

happy31
7 Apr 2008, 12:09 AM
excellent......:)
but can this DWRProxy working with paging?:-/

gordosity
7 Apr 2008, 10:54 AM
Thanks for the excellent extension. I've used it to load data from my Java class on the server (ie. MyJavaClass.getList(), which returns an object with two items: a record count and an ArrayList of Java objects) and I've loaded that data into an EditorGridPanel.

Forgive me for being dense, but after I've made changes to grid and I click on a button to Save the grid changes..... how do I get the data back to the server? How do I get the proxy to execute MyJavaClass.setList(list)??

I've been reading through APIs and forums for days, but I still don't so any connection.

Thanks in advance for any help.

gordosity
8 Apr 2008, 5:45 AM
I get the store, read each record, convert it to JS object, then use a direct DWR call to update the record in the HashMap in my Java class (ie. MyJavaClass.updateGridList(record)). The conversion from JS to Java object is handled by DWR.

loeppky
8 Apr 2008, 3:54 PM
but can this DWRProxy working with paging?:-/

happy31: this is nothing that prevents DWRProxy to work with paging. Paging is done by passing params to the load method for the proxy that state the start record and the number of records to return. Grids, for example, have a convention for what these parameters are named. You can listen to the 'beforeload' event that DWRProxy fires, and then extract the paging parameters from the params object that is passed with 'beforeload'.

I don't have bandwidth at the moment to whip up an example, but I hope that makes sense.

happy31
8 Apr 2008, 7:49 PM
happy31: this is nothing that prevents DWRProxy to work with paging. Paging is done by passing params to the load method for the proxy that state the start record and the number of records to return. Grids, for example, have a convention for what these parameters are named. You can listen to the 'beforeload' event that DWRProxy fires, and then extract the paging parameters from the params object that is passed with 'beforeload'.

I don't have bandwidth at the moment to whip up an example, but I hope that makes sense.

thanks.....;) it helps a lot

Fretzer
11 Apr 2008, 12:47 AM
I have a question; Why is the DWRProxy not found in the 'official' extension list of ExtJS Extensions?

Kind regards,
Fretzer

loeppky
11 Apr 2008, 8:02 AM
Fretzer: it hasn't been listed in the Ext extensions due to a lack of time on my part. When I get my current project done in a couple of weeks, I will hopefully have a bit of slack to do such things. That said, it would totally fine if you wanted to go ahead an setup the extension page. If someone got it started, I would be more prone to to contribute :)

sachin_y
17 Apr 2008, 2:39 AM
Hi loeppky,

I am facing a problem with DWRProxy developed by you. My data grid doesn't populate any result, when i debug the code i found that load: method of the proxy fires one request but loadResponse: never gets executed and this is why we didn't get any result back.

My DWR response is properly formated and as below:



//#DWR-INSERT //#DWR-REPLY var s1=[];var s2={};var s0={};var s3={};var s4={};var s5={};s1[0]=s2;s1[1]=s3;s1[2]=s4;s1[3]=s5; s2.date="04/25/08";s2.destination="dsa";s2.flight=s0;s2.source="asd"; s0.airlineName="Air America";s0.flightNo="A440"; s3.date="04/25/08";s3.destination="dsa";s3.flight=s0;s3.source="asd"; s4.date="04/25/08";s4.destination="dsa";s4.flight=s0;s4.source="asd"; s5.date="04/25/08";s5.destination="dsa";s5.flight=s0;s5.source="asd"; dwr.engine._remoteHandleCallback('0','0',{data:s1,totalSize:2});

Can you please take a look at it and tell me what's going wrong there.

loeppky
17 Apr 2008, 9:59 AM
sachin_y: two things to look at:


Make sure the dwrFunctionArgs are getting built up correctly. These should be same as if you were executling your DWR method direclty.
Set a breakpoint within the callback. Do you make it into there?

sachin_y
17 Apr 2008, 7:36 PM
sachin_y: two things to look at:

Make sure the dwrFunctionArgs are getting built up correctly. These should be same as if you were executling your DWR method direclty.
Set a breakpoint within the callback. Do you make it into there?

Loeppky Thanks for your reply.

1. Yes DWR request and response are same as if executed DWR method direclty.
2. I don't know how to set breakpoint in firebug. I can't see my script in script section so that i can put a breakpoint there.

However i am putting up more code, as i am suspected that there is some problem in ExtJS code.

I am using viewport and onClick of a button from west region will populate the grid in the center region named as "result".

index.js (main page)




Ext.onReady(function(){
Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
Ext.QuickTips.init();
var viewport = new Ext.Viewport({
layout:'border',
items:[
new Ext.BoxComponent({ // raw
region:'north',
el: 'north',
height:32
}),{
region:'south',
contentEl: 'south',
split:true,
height: 100,
minSize: 100,
maxSize: 200,
collapsible: true,
title:'South',
margins:'0 0 0 0'
},

{
region:'west',
title:'Search / Book Itenary',
split:true,
width: 300,
minSize: 175,
maxSize: 300,
//layout: 'fit',
collapsible: true,
margins:'0 0 0 5',
layout:'accordion',
layoutConfig:{
animate:true
},
items: [{
title:'Air Search',
border:false,
iconCls:'settings',
items: [{
xtype: 'panel',
height: 300,
width: 300,
layout: 'fit',
items: new Ext.form.FormPanel({
labelWidth: 75,
bodyStyle: 'padding:5px;',
defaultType: 'textfield',
items: [{
fieldLabel: 'Source',
id: 'source',
name: 'src',
maxLength:3,
minLength:3,
minLengthText:'Only 3 Characters Accepted',
allowBlank:false
}, {
fieldLabel: 'Destination',
id: 'destination',
maxLength:3,
minLength:3,
minLengthText:'Only 3 Characters Accepted',
allowBlank:false,
name: 'dst'
}, {
xtype: 'datefield',
allowBlank:false,
fieldLabel: 'Date',
name: 'date',
id: 'date'
}, {
xtype:'button',
text: 'Search',
id:'searchFlight',
handler: function(){

//This will initialize and set the grid in center

Ext.onReady(GridUI.init, GridUI, true);
}
}]
})
}]
},{
title:'Customer Profile',
html:'<p>Some settings in here.</p>',
border:false,
iconCls:'settings'
}]
},
new Ext.TabPanel({
region:'center',
deferredRender:false,
activeTab:0,
items:[{
contentEl:'result',
title: 'Search Results',
autoScroll:true
}]
})
]
});
});



my airSearchResuoltGrid.js Page



var GridUI = function() {
var ds;
var grid; //component
var columnModel; // definition of the columns
function initDataSource() {
var recordType = Ext.data.Record.create([
{name: "source", width: 120,type: "String"},
{name: "destination", width: 120, type: "string"},
{name: "airlinename", mapping:"flight.airlineName", width: 120, type: "string"},
{name: "flightno", mapping:"flight.flightNo", width: 120, type: "string"}
]);

ds = new Ext.data.Store({
proxy: new Ext.data.DWRProxy(DWRLogin.checkResult,true),
reader: new Ext.data.ListRangeReader(
{id:'source', totalProperty:'totalSize'}, recordType),
remoteSort: true
});
ds.on("load", this.onLoad, this);
}

function getColumnModel() {
alert("step3");
if(!columnModel) {
columnModel = new Ext.grid.ColumnModel(
[
{
header: 'Source',
width: 250,
sortable: true,
dataIndex: 'source',
editor: new Ext.form.TextField({
allowBlank: false
})
},
{
header: 'Destination',
width: 250,
sortable: true,
dataIndex: 'destination'
},
{
header: 'Airline Name',
width: 250,
sortable: true,
dataIndex: 'airlinename'
},
{
header: 'Airline NO',
width: 250,
sortable: true,
dataIndex: 'flightno'
}
]
);
}
return columnModel;
}

function buildGrid() {
grid = new Ext.grid.GridPanel({
ds: ds,
viewConfig: {forceFit: true},
cm: getColumnModel(),
stripeRows: true,
sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
height:350,
width:600,
//collapsible: true,
title:'Grid'
});

grid.render('result');
}


return {
init : function() {
initDataSource();

// Please look here i don't know if this is write or not.
ds.load({params:{start:0, limit:22}, arg:[$("source").value,$("destination").value,$("date").value,true]});
buildGrid();
},

getStore: function() {
return ds;
}
}
}();

//called from index.js on button click
// Ext.onReady(GridUI.init, GridUI, true);




My java class file is:




/*
* ListRange is a bean with only getter/setters for Data and TotalSize.
*/
public ListRange checkResult(String source, String destination, String date, boolean flag, int start, int count){

ListRange listRange = new ListRange();

Flight flightVO = new Flight("A440","Air America");
Object[] data = {new AirSearchVO(source,destination,date,flightVO),new AirSearchVO(source,destination,date,flightVO),
new AirSearchVO(source,destination,date,flightVO),new AirSearchVO(source,destination,date,flightVO)};

listRange.setData(data);
listRange.setTotalSize(2);


return listRange;

}

}




I think i am screwed somewhere is calling grid into the result div of main page.

ThomasBecker
18 Apr 2008, 2:09 AM
Hi loeppky, Hi community,

first of all thanks for the nice work and for supporting the community! I really don't want to bother you more than necessary, but I'm kinda stuck as well.


load: function(params, reader, loadCallback, scope, arg){

gets executed. dwrFunctionArgs.push puts the callback and exception handler to dwrFunctionArgs.

The dwr call is being made and gets:


//#DWR-INSERT

//#DWR-REPLY

var s0=[];var s1={};var s2={};var s3={};var s4={};var s5={};var s6={};s0[0]=s1;s0[1]=s2;s0[2]=s3;s0[3

]=s4;s0[4]=s5;s0[5]=s6;

s1.id="4";s1.description="Tag denoting an artist";s1.key="ARTIST";

s2.id="1";s2.description="Tag denoting a genre";s2.key="GENRE";

s3.id="5";s3.description="Tag denoting a keyword";s3.key="KEYWORD";

s4.id="8";s4.description="category-tags for editorial news content";s4.key="NEWSCATEGORY";

s5.id="3";s5.description="Tag denoting a price";s5.key="PRICE";

s6.id="2";s6.description="Tag denoting a subgenre";s6.key="SUBGENRE";

dwr.engine._remoteHandleCallback('1','0',{data:s0,totalSize:6});

Which is the expected response. But store.data.items stays empty and so does the combobox.

Here's the ext code I'm using:


Ext.extend(Moritz.EditorialContentModule.CreateTagForm, Moritz.EditorialContentBase, {
form: null,

init : function() {
Moritz.EditorialContentModule.EventContentDetailsNews.superclass.init.call(this);
me = this;
},

// Create Grid which contains all tags belonging to the client
createDetailPanel: function (eventId, theEventName, parentContentView){

var dsCmbTagTypes = new Ext.data.Store({
proxy: new Ext.ux.data.DWRProxy({
dwrFunction: TagTypeDwrController.getTagTypes,
listeners: {
'beforeload': function(dataProxy, params){
// setting the args that will get passed to the DWR function
params[dataProxy.loadArgsKey] = ['query'];
}
}
}),

reader: new Ext.data.JsonReader({
totalProperty: "totalSize",
root: "data"
}, [
{name: 'id', mapping: 'id'},
{name: 'key', mapping: 'key'},01797703944/mms123
]),
});

var cmbTagType = new Ext.form.ComboBox({
fieldLabel: 'Tag (Position)',
triggerAction: 'all',
hiddenName: 'tagId',
allowBlank: true,
editable: false,
mode: 'remote',
store: dsCmbTagTypes,
displayField: 'key',
valueField: 'id',
emptyText: 'Select tag',
width:190
});

cmbTagType.on("expand", this.onExpand, this);

this.form = new Ext.form.Form({
labelAlign: 'right',
labelWidth: 100,
url: 'editorialContent/readEditorialContentData.groovy',
baseParams: {
reqType: 'competition',
id: id
},
reader: new Ext.data.JsonReader({
root: 'items',
totalProperty: 'totalCount',
id: 'id'
}, [
{name: 'tagKey'},
{name: 'tagDescription'},
{name: 'tagType'},
])

});
this.form.column({
style: 'width: 540px;'
});
this.form.fieldset(
{legend:'Tag',
style: 'width: 500px; margin: 10px; padding: 10px;'
});

this.form.add(
cmbTagType);
...snipsnap...

I'm really stuck here. Tried to debug it step by step for hours with no step forward. :( Any help is greatly appreciated. If someone is interested in the backend java code, let me know. I'll post it then.

Thanks a lot,
Thomas

sachin_y
18 Apr 2008, 5:04 AM
Hi Thomas,

Why don't you use the ListReader? Can you paste some java code may be i can help with it.

sachin_y
18 Apr 2008, 6:17 AM
loeppky:

I did get manage to get atleast loadResponse in DWRProxy, i saw that i had 1 less parameter in my java class as compare to what i was sending. But now i am getting exception in loadresponse.




callParams : ["asd", "dsa", "04/19/08", true, 0, 22, "", function()]
_debug("Error: ReferenceError, response is not defined", true)engine.js (line 1223)
defaultErrorHandler("response is not defined", ReferenceError: response is not defined message=response is not defined)engine.js (line 177)
_handleError(Object map=Object charsProcessed=0 paramCount=0, ReferenceError: response is not defined message=response is not defined)engine.js (line 1008)
_remoteHandleCallback(undefined, undefined, undefined)engine.js (line 878)
_eval("//#DWR-INSERT\r\n//#DWR-REPLY\r\nvar s0=[];var s1={};var s5={};var s2={};var s6={};var s3={};var s7={};v...")engine.js (line 939)
_stateChange(Object map=Object charsProcessed=0 paramCount=0)engine.js (line 855)
onreadystatechange()engine.js (line 652)

Error: ReferenceError, response is not defined



in my java i added order by param in my funtion like this:




public ListRange checkResult(String source, String destination, String date, boolean flag, int start, int count, String orderBy)



What do you suggest here.

loeppky
18 Apr 2008, 8:46 AM
Thomas: set a breakpoint within the DWRProxy callback function at the line that says:"var records = reader.readRecords(response);". Check to make sure that "response" looks good and make sure that "records" gets set appropriately after the "readRecords" call. If it doesn't, then you need to step into that method. It really looks like you've configured DWRProxy to work correctly, but maybe not something else.

loeppky
18 Apr 2008, 8:53 AM
sachin_y: you have many things wrong. Here are a couple:

You aren't instantiating DWRProxy correctly. DWRProxy takes a single a parameter, a config object, where you defint the dwrFunction. Look at what Thomas is doing or the example I posted in post #2.
I've never heard of the ListReader before. Where is that defined? I don't see it in the APIs.


It's totally fine that you're new at this stuff, but as with anything when learning, I'd advise that you start small and build up from there. In post #2, I have a sample. You can use that a starting place. Other people have posted some examples as well that use a grid. Instead of having a function that takes 7 parameters, start with a test function that takes 1 parameter. Once you get that working, build up from there.

If you need help setting Firebug breakpoints, go to the Firebug website and read the docs. I'm pretty sure it's explained there. That will be an invaluable tool to have as you move forward with JavaScript development.

Good luck!
Steve

sachin_y
18 Apr 2008, 10:50 AM
Steve:

Thank's again for your suggestions. Can yuo please tell me how can i send three params like "src", "des", "date" to my java file using DWRProxy. right now i send them like



ds.load({params:{start:0, limit:22}, arg:[$("source").value,$("destination").value,$("date").value,true]});

and if i try to do something like:



proxy: new Ext.data.DWRProxy({
dwrFunction: DWRLogin.checkResult,
listeners: {
'beforeload': function(dataProxy, params){
// setting the args that will get passed to the DWR function
params[dataProxy.loadArgsKey] = [$("source").value,$("destination").value,$("date").value];
}
}
}),

I START GETTING ERROR AS this.dwrCall.apply is not a function.

Please tell me how do i resolve this. In the mean time i have learned how to use debugger and also i already have one basic data grid build but that doesn't send any parameters and only fetch data from java files, but in this case i have to send 3 parameters for database query, and this is where i am badly stuck.

sachin_y
18 Apr 2008, 10:58 AM
I've never heard of the ListReader before. Where is that defined? I don't see it in the APIs.

I was talking about Ext.data.ListRangeReader ;), sorry for typo. :D

loeppky
18 Apr 2008, 11:59 AM
sachin_y: you need to store "[$("source").value,$("destination").value,$("date").value,true]" so you can access them in the "beforeload" listener. Sticking them in the params should work as those params get passed to the "beforeload" listener.

trmcmichael
18 Apr 2008, 4:19 PM
I started working with ExtJS recently to replace some of the less attractive and functional portions of my web apps. I have the grid working well until I introduced Hibernate into my project.

Here are my tools:
MyEclipse 6
Oracle 10g
DWR / DWRproxy (thanks to you guys!)
Hibernate 3.1
Geronimo 2

My JS file:

//Ext.onReady(function() {

// Global Variables

// Grid Function
function getGrid() {
// Create the JSON reader
var reader = new Ext.data.JsonReader({
totalProperty: "totalSize",
root: "data"
}, Ext.data.Record.create([
{ name: "column1", type: "string" },
.......
]));

// Create the Row Expander / Column Collapser
var xg = Ext.grid;
var expander = new xg.RowExpander({
tpl : new Ext.Template(
'<p><b>Company:</b> {company}<br>',
'<p><b>Summary:</b> {desc}</p>')
});

// Create the data store and define the DWR proxy
var store = new Ext.data.Store({
proxy:new Ext.ux.data.DWRProxy({
dwrFunction: App.list,
listeners: {
'beforeload': function(dataProxy, params){
// setting the args that will get passed to the DWR function
params[dataProxy.loadArgsKey] = [params.start, params.limit];
}
}
}),
reader: reader,
remoteSort: false
});

// Create the columns and parameters
var columns = [expander,{
"header": "column1",
"dataIndex": "column1_index",
"sortable": "true",
"id": "column1_id",
"width": 75
}, ...........
}];
columns.defaultSortable = true;

// Create the Grid
var grid = new Ext.grid.GridPanel({
store: store,
columns: columns,
title: 'Array Grid',
stripeRows: true,
viewConfig: { forceFit: true },
height: 400,
width: 725,
plugins: expander, // expander attribute
collapsible: true, // expander attribute
frame: true,
// Create the footer navigation bar
bbar: new Ext.PagingToolbar({
store: store,
pageSize: 25,
displayInfo: true,
displayMsg: 'Displaying records {0} - {1} of {2}',
emptyMsg: "No results to display"
})
});
grid.render ('content');
store.load ({params:{start:0, limit:25}});
grid.getSelectionModel().selectFirstRow();
}
//});

DWRProxy:

/**
* http://extjs.com/forum/showthread.php?t=19529
*/
Ext.namespace("Ext.ux.data");

/**
* @class Ext.ux.data.DWRProxy
* @extends Ext.data.DataProxy
* @author loeppky
* An implementation of Ext.data.DataProxy that uses DWR to make a remote call.
* @constructor
* @param {Object} config A configuration object.
*/
Ext.ux.data.DWRProxy = function(config){
Ext.apply(this, config); // necessary since the superclass doesn't call apply
Ext.ux.data.DWRProxy.superclass.constructor.call(this);
};

Ext.extend(Ext.ux.data.DWRProxy, Ext.data.DataProxy, {

/**
* @cfg {Function} dwrFunction The DWR function for this proxy to call during load.
* Must be set before calling load.
*/
dwrFunction: null,

/**
* @cfg {String} loadArgsKey Defines where in the params object passed to the load method
* that this class should look for arguments to pass to the "dwrFunction".
* The order of arguments passed to a DWR function matters.
* Must be set before calling load.
* See the explanation of the "params" parameter for the load function for further explanation.
*/
loadArgsKey: 'dwrFunctionArgs',

/**
* Load data from the configured "dwrFunction",
* read the data object into a block of Ext.data.Records using the passed {@link Ext.data.DataReader} implementation,
* and process that block using the passed callback.
* @param {Object} params An object containing properties which are to be used for the request to the remote server.
* Params is an Object, but the "DWR function" needs to be called with arguments in order.
* To ensure that one's arguments are passed to their DWR function correctly, a user must either:
* 1. call or know that the load method was called explictly where the "params" argument's properties were added in the order expected by DWR OR
* 2. listen to the "beforeload" event and add a property to params defined by "loadArgsKey" that is an array of the arguments to pass on to DWR.
* If there is no property as defined by "loadArgsKey" within "params", then the whole "params" object will be used as the "loadArgs".
* If there is a property as defined by "loadArgsKey" within "params", then this property will be used as the "loagArgs".
* The "loadArgs" are iterated over to build up the list of arguments to pass to the "dwrFunction".
* @param {Ext.data.DataReader} reader The Reader object which converts the data object into a block of Ext.data.Records.
* @param {Function} callback The function into which to pass the block of Ext.data.Records.
* The function must be passed <ul>
* <li>The Record block object</li>
* <li>The "arg" argument from the load function</li>
* <li>A boolean success indicator</li>
* </ul>
* @param {Object} scope The scope in which to call the callback
* @param {Object} arg An optional argument which is passed to the callback as its second parameter.
*/
load: function(params, reader, loadCallback, scope, arg){
var dataProxy = this;
if (dataProxy.fireEvent("beforeload", dataProxy, params) !== false) {
var loadArgs = params[this.loadArgsKey] || params; // the Array or Object to build up the "dwrFunctionArgs"
var dwrFunctionArgs = []; // the arguments that will be passed to the dwrFunction
if (loadArgs instanceof Array) {
// Note: can't do a foreach loop over arrays because Ext added the "remove" method to Array's prototype.
// This "remove" method gets added as an argument unless we explictly use numeric indexes.
for (var i = 0; i < loadArgs.length; i++) {
dwrFunctionArgs.push(loadArgs[i]);
}
} else { // loadArgs should be an Object
for (var loadArgName in loadArgs) {
dwrFunctionArgs.push(loadArgs[loadArgName]);
}
}
dwrFunctionArgs.push({
callback: function(response){
// call readRecords verses read because read will attempt to decode the JSON,
// but as this point DWR has already decoded the JSON.
var records = reader.readRecords(response);
dataProxy.fireEvent("load", dataProxy, response, loadCallback);
loadCallback.call(scope, records, arg, true);
},
exceptionHandler: function(message, exception){
// the event is supposed to pass the response, but since DWR doesn't provide that to us, we pass the message.
dataProxy.fireEvent("loadexception", dataProxy, message, loadCallback, exception);
loadCallback.call(scope, null, arg, false);
}
});
this.dwrFunction.apply(Object, dwrFunctionArgs); // the scope for calling the dwrFunction doesn't matter, so we simply set it to Object.
} else { // the beforeload event was vetoed
callback.call(scope || this, null, arg, false);
}
}
});

Java App:

package mypackage;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class App {
static SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

public App() {
}

@SuppressWarnings({ "unused", "unchecked" })
public static Map<String, Object> list(int start, int limit) {
Session session = sessionFactory.openSession();
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
HashMap<String, Object> row;
HashMap<String, Object> map = new HashMap<String, Object>();
String sqlquery = "some sql here";
List results = session.createQuery(sqlquery)
.setFirstResult(start)
.list();
int count = results.size();
Iterator results2 = results.iterator();
for (int i = 1; i <= limit; i++) {
Object[] tuple = (Object[]) results2.next();
row = new HashMap<String, Object>();
row.put("col1", tuple[0]);row.put("col2", tuple[1]);
row.put("col3", tuple[2]);row.put("col4", tuple[3]);
row.put("col5", tuple[4]);row.put("col6", tuple[5]);
row.put("col7", tuple[6]);list.add(row);
}
session.close();
map.put("totalSize", count);
map.put("data", list);
return map;
}
}

The error I receive in Geronimo console:

16:09:38,867 ERROR [[dwr-invoker]] Servlet.service() for servlet dwr-invoker threw exception
java.lang.ClassCastException: java.util.HashSet cannot be cast to java.lang.String
at org.hibernate.util.PropertiesHelper.resolvePlaceHolders(PropertiesHelper.java:88)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1173)
at mypackage.App.<clinit>(App.java:14)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.directwebremoting.impl.ExecuteAjaxFilter.doFilter(ExecuteAjaxFilter.java:34)
at org.directwebremoting.impl.DefaultRemoter$1.doFilter(DefaultRemoter.java:428)
at org.directwebremoting.impl.DefaultRemoter.execute(DefaultRemoter.java:431)
at org.directwebremoting.impl.DefaultRemoter.execute(DefaultRemoter.java:283)
at org.directwebremoting.servlet.PlainCallHandler.handle(PlainCallHandler.java:52)
at org.directwebremoting.servlet.UrlProcessor.handle(UrlProcessor.java:101)
at org.directwebremoting.servlet.DwrServlet.doPost(DwrServlet.java:146)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:713)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:806)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.geronimo.tomcat.valve.DefaultSubjectValve.invoke(DefaultSubjectValve.java:56)
at org.apache.geronimo.tomcat.GeronimoStandardContext$SystemMethodValve.invoke(GeronimoStandardContext.java:396)
at org.apache.geronimo.tomcat.valve.GeronimoBeforeAfterValve.invoke(GeronimoBeforeAfterValve.java:47)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:563)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:584)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Thread.java:619)


If this is not the right place to post this, I appologize
Ty

sachin_y
18 Apr 2008, 9:42 PM
Hi steve,

Sorry for bothering you again. I have changed my code a bit. I am using now the DWRProxy posted by you in post#2 and now my js looks like this:



function initDataSource() {
var recordType = Ext.data.Record.create([
{name: "source", width: 120,type: "String"},
{name: "destination", width: 120, type: "string"},
{name: "airlinename", mapping: "flight.airlineName", width: 120, type: "string"},
{name: "flightno", mapping: "flight.flightNo", width: 120, type: "string"}
]);

var reader = new Ext.data.JsonReader({

totalProperty: "totalSize",
root: "data",
id: "source"
}, recordType);


ds = new Ext.data.Store({
proxy: new Ext.data.DWRProxy({
dwrFunction: DWRLogin.checkResult,
listeners: {
'beforeload': function(dataProxy, params){
params.source = $("source").value;
params.destination = $("destination").value;
params.date = $("date").value;
params.flag = true;
params.start = 0;
params.limit = 22;
params.orderBy = "";
params[dataProxy.loadArgsKey] = [params.source, params.destination, params.date, params.flag, params.start, params.limit, params.orderBy];
}
}
}),
reader: reader,
});

ds.on("load", function () {
});
at line : var records = reader.readRecords(response); in dwrproxy is got an error :



//#DWR-INSERT//#DWR-REPLYvar s0=[];var s1={};var s5={};var s2={};var s6={};var s3={};var s7={};var s4={};var s8={};s0[0]=s1;s0[1]=s2;s0[2]=s3;s0[3]=s4;s1.date="04/18/08";s1.destination="dsa";s1.flight=s5;s1.source="asd";s5.airlineName="Air America";s5.flightNo="A440";s2.date="04/18/08";s2.destination="dsa";s2.flight=s6;s2.source="asd";s6.airlineName="Air India";s6.flightNo="A420";s3.date="04/18/08";s3.destination="dsa";s3.flight=s7;s3.source="asd";s7.airlineName="Air Canada";s7.flightNo="A450";s4.date="04/18/08";s4.destination="dsa";s4.flight=s8;s4.source="asd";s8.airlineName="Air Taiwan";s8.flightNo="A140";dwr.engine._remoteHandleCallback('0','0',{data:s0,totalSize:4});
_debug("Error: TypeError, R.convert is not a function", true)engine.js (line 1223)


defaultErrorHandler("R.convert is not a function", TypeError: R.convert is not a function message=R.convert is not a function)engine.js (line 177)


_handleError(Object map=Object charsProcessed=0 paramCount=0, TypeError: R.convert is not a function message=R.convert is not a function)engine.js (line 1008)


_remoteHandleCallback(undefined, undefined, undefined)engine.js (line 878)


_eval("//#DWR-INSERT\r\n//#DWR-REPLY\r\nvar s0=[];var s1={};var s5={};var s2={};var s6={};var s3={};var s7={};v...")engine.js (line 939)


_stateChange(Object map=Object charsProcessed=0 paramCount=0)engine.js (line 855)
onreadystatechange()engine.js (line 652)



Error: TypeError, R.convert is not a function

I am attaching the screen shot of firebug console. Can you please look at it and let me know what might be the cause.

sachin_y
19 Apr 2008, 11:21 AM
Ok, i have done this. Thanks steve for your constant support.

ThomasBecker
21 Apr 2008, 1:59 AM
@Loeppky: dwrFunctionArgs gets filled with the callback, but it seems like the callback never gets executed?! How can i find out why or where shall I have a look? Sorry, if that's a stupid question...I'm still new to ext.
@Michael: You've got a problem outside DWR in your java code.

The exception you get says that at mypackage.App.<clinit>(App.java:14) you're trying to cast a HashSet to String, which is not possible. Actually this is not the right place to ask, however have a look at your code:

Your clas returns a: Map<String, Object>
However you're building:

List<Map<String, Object>> list
and
HashMap<String, Object> map

Then you're filling row, put row into list and try to return it as a Map<String, Object>. But what you've got in map at the end is a:
HashMap<String, List<HashMap<String, Object>>>

Mhh maybe not exactly thata. Your code confused me. :) However you see the problem?

s_kumar
21 Apr 2008, 2:44 AM
Hi loeppky,

I have created a grid using extjs,DWRProxy and Java. and it's working fine. but now i am having a collection inside collection as a response object from java. Kindly suggest me how to do the mapping in Ext.data.Record.create for collection inside collection Object?

Thanks in advanced.

ThomasBecker
21 Apr 2008, 8:20 AM
I'm wondering that I still have that much hair to torn out. ;)

@loeppky: Stupid question...which I should have asked myself way earlier...could my problem be due to the fact that I'm using ext 1.1.1? *blushes*

loeppky
21 Apr 2008, 8:54 AM
ThomasBecker: I haven't tested this with Ext 1.1.1, so it very well may be. I'm not going to have the bandwidth either to support Ext 1.1.1.

loeppky
21 Apr 2008, 8:55 AM
s_kumar: I don't recall offhand how to do the mapping in Ext.data.Record.create for collection inside collection Object. As that's not a DWRProxy specific issue, I'm sure you'll be able to find the answer in the APIs or in another post.

loeppky
21 Apr 2008, 8:56 AM
sachin_y: so are things working for you now?

sachin_y
21 Apr 2008, 8:59 AM
sachin_y: so are things working for you now?

Yes steve things are working find now to my end. Thanks for your support.\:D/=D>

ThomasBecker
22 Apr 2008, 4:31 AM
@loeppky: I don't think anymore that my problem relates to the fact I'm using ext1.1.1. I tried your example and it works fine. So I replaced the dwr call from my old code:


var dsCmbTagTypes = new Ext.data.Store({
proxy: new Ext.ux.data.DWRProxy({
dwrFunction: TagTypeDwrController.getTagTypes,
listeners: {
'beforeload': function(dataProxy, params){
// setting the args that will get passed to the DWR function
params[dataProxy.loadArgsKey] = ['loeppkyIsMyUserId', params.query];
}
}
}),

reader: new Ext.data.JsonReader({
totalProperty: "totalSize",
root: "data"
}, [
{name: 'id', mapping: 'id'},
{name: 'key', mapping: 'key'},
{name: 'description', mapping: 'description'}
]),
});

With:


dwrFunction: DWRProxySampleInterface.getPossibleBusinessGroups,

And see my breakpoint at "var records = reader.readRecords(response);" hits and I surely get an error message, since there's no data and totalsize in the response. However if I call my DWR method it requests the dwr page and this is returned:


//#DWR-INSERT

//#DWR-REPLY

var s0=[];var s1={};var s2={};var s3={};var s4={};var s5={};var s6={};s0[0]=s1;s0[1]=s2;s0[2]=s3;s0[3

]=s4;s0[4]=s5;s0[5]=s6;

s1.id="4";s1.description="Tag denoting an artist";s1.key="ARTIST";

s2.id="1";s2.description="Tag denoting a genre";s2.key="GENRE";

s3.id="5";s3.description="Tag denoting a keyword";s3.key="KEYWORD";

s4.id="8";s4.description="category-tags for editorial news content";s4.key="NEWSCATEGORY";

s5.id="3";s5.description="Tag denoting a price";s5.key="PRICE";

s6.id="2";s6.description="Tag denoting a subgenre";s6.key="SUBGENRE";

dwr.engine._remoteHandleCallback('1','0',{data:s0,totalSize:6});

Which looks exactly as something what JSONReader would expect, wouldn't it? However the breakpoint at "var records = reader.readRecords(response);" never gets hit and this means that the callback never gets executed.

Do you have any idea what the reason could be and/or how I can further debug this? I really have no idea anymore. :(

ThomasBecker
22 Apr 2008, 8:10 AM
Ok, now I'm really really confused. First of all it works...but I don't get it...

I migrated step by step from your example to my code. And here's the difference between working and not working:

Method signature in my java class:

public Map<String, Object> getTagTypes(String userId, String query) {

JS:

params[dataProxy.loadArgsKey] = ['loeppkyIsMyUserId', params.query];

This is the working version. And this was the java class before:


public Map<String, Object> getTagTypes() {

Strange thing however is, and that's why I didn't verified anything in my controller before, that the response of the dwr call is exactly the same with both versions. I also neither use userId nor query in the java method.

I really would like to understand what the problem is. So if you folks could shed some light on me. If you want I post my whole stuff again now as yet another working example for ComboBox.

loeppky
23 Apr 2008, 8:25 AM
ThomasBecker: this has to do with how DWR works. Let's use your example:


public Map<String, Object> getTagTypes(String userId, String query)

In this case, your Java method has two arguments. When you invoke this Java method remotely through DWR, DWR is expecting three arguments: userId, query, and callback. In the original case where you Java method was


public Map<String, Object> getTagTypes()

DWR is expecting one argument: callback. You originally had the 0 argument version in Java ("public Map<String, Object> getTagTypes()") but were passing it 3 arguments. In this case DWR ignored the last two arguments, and expected the first to be the callback, which was no callback at all since it was the userid.

Make sense?

ThomasBecker
23 Apr 2008, 9:38 AM
Absolutely. :) Got it all. Working with your DWRProxy works like a charm now. Cool thing. Thanks for your work, great and nice support!

I've a general question. How do you guys handle form submits to your backend? Do you use dwr controllers for forms as well?

alexis2008
25 Apr 2008, 10:56 PM
Hi,

I would like to use this amazing proxy but I have some little troubles.

First, this is my server side :


public class Service {

public List list(String startOfTheName) {
List l = new ArrayList();

List p1 new ArrayList();
p1.add("1");
p1.add(startOfTheName + "qsjfj");

List p2 new ArrayList();
p2.add("2");
p2.add(startOfTheName + "qsjfj");

l.add(p1);
l.add(p2);

return l;
end


It returns an ArrayList of ArrayList

I've got a combo :


var combo = new Ext.form.ComboBox({
store: store,
typeAhead: true,
mode: 'remote',
triggerAction: 'all',
emptyText:'Select a name...',
selectOnFocus:true,
applyTo: 'combo-name',
displayField: 'name',
queryParam: 'query',
});


And this is my proxy :


var proxy = new Ext.ux.data.DWRProxy({
dwrFunction: Service.list,
listeners: {
'beforeload': function(dataProxy, params){
alert(params.query);
params[dataProxy.loadArgsKey] = [params.query];
}
}
});


But params.query is empty... The value I want to use is the display value of the combo box, but it doesn't seem to work... Can you help me ?

There is another thing but I can deal with. The method List return an ArrayList of ArrayList. It work fine. But I would like to have an ArrayList of beans and I don't know how to use the proxy without an ArrayReader...

So, this work fine, but not with an Array of bean...


var data = Ext.data.Record.create([
{name: 'pk'},
{name: 'name'}
])

var reader = new Ext.data.ArrayReader({}, data);

var store = new Ext.data.Store({
proxy: proxy,
reader: reader});

Maybe I have a problem of converters with DWR...



public List list(String startOfTheName) {
List l = new ArrayList();

Person p1 new Person();
p1.setPk("1");
p1.setName(startOfTheName + "qsjfj");

Person p2 new Person();
p2.setPk("2");
p2.setName(startOfTheName + "qsjfj");

l.add(p1);
l.add(p2);

return l;
end

I'm sure I miss something very simple... but I dont' know what....

Thanks to anynone you can help !!!

alexis2008
27 Apr 2008, 11:25 AM
=; Sorry, forget every thing, it's easy to use =D>

ThomasBecker
28 Apr 2008, 12:45 AM
It's probably easier to not convert your beans to javascript object, but to fill a map in your controller which fits to a format which ext expects. Just see my example for reference and use JSONReader in ext. Works pretty fine for me.

Not sure if you can do word completion in a combobox as you seem to try. In my variant ext is doing exactly one XMLHttpRequest to fill the options of the combobox and that's it.

I have to set one parameter which is the contractId and I do it as follows:


'beforeload': function(dataProxy, params){
// setting the args that will get passed to the DWR function
params[dataProxy.loadArgsKey] = [1, moritz.currentContract.id];
}

dddu88
2 May 2008, 9:16 PM
Hi, all
I have the code as this:

this.store = new Ext.data.Store({
proxy: new Ext.ux.data.DWRProxy({
dwrFunction: UserHandler.getUserFiles,
listeners: {
'beforeload': function(dataProxy, params){
// setting the args that will get passed to the DWR function
params.url = $("url").value;
params.Id = $("Id").value;

params[dataProxy.loadArgsKey] = [params.url, params.Id];
}
}
}),

reader: new Ext.data.ArrayReader({}, recordType)


});

and the load function call:

this.store.load({arg:[url, Id]});

But both url and Id can not be passed to the function load: function(params, reader, loadCallback, scope, arg) of DWRProxy, from firebug debugger after

var loadArgs = params[this.loadArgsKey] || params;

I can see loadArgs has two undefined items, then it gave me error: root has no property.

so what is the right way to pass parameters? I tried different ways, but no success, my java side method was not even called, which is like this:


public ArrayList getUserFiles(String uri, String Id){.

Thanks in advance.

Dave

dddu88
2 May 2008, 9:37 PM
Ok, I just passed in the parameters by using this:



params.url = url;
params.Id = Id;
params[dataProxy.loadArgsKey] = [params.url, params.Id];

Now I got Error: TypeError, f.convert is not a function.

my recordType is:

var recordType = Ext.data.Record.create([
{name:'name', type:"string"},
{name:'size', type: 'long'},
{name:'lastmod', type: 'string'}
]);


any suggestion?
Thanks
Dave

dddu88
3 May 2008, 5:22 PM
I found out the type long for size is not correct in javascript, which caused this error.

Thanks

Dave

marvelousgame
6 May 2008, 8:50 PM
Hi folks,

This version of DWRProxy seems working perfectly with me.

But I got some problem regarding the store (I don't know whether this is DWRProxy or Ext Js problem)

Here is the big view:
1. After store.load() statement, DWRProxy return me the data.
The data's format is: [["Hello, abc"]]

2. Try to get the data's value:


var dataRecord = store.getAt(0);
var dataValue = dataRecord.json;
alert(dataValue);

And I get error in firebug: "dataRecord has no properties"

But if I add an alert statement before store.getAt(0);


alert("Data Loaded"); //Add alert statement
var dataRecord = store.getAt(0);
var dataValue = dataRecord.json;
alert(dataValue);

I can retrieve the value perfectly, and will pop up "Hello, abc"

I also try to set breakpoints in firebug.(without alert code)
And it seems to work properly after I step over to the next step until it stops.

Any suggestions???

Any help will be appreciated!

marvelousgame
7 May 2008, 2:15 AM
It must wait until the data loaded into the store (In API of Ext.data.Store load described)

In case any of you need it, you must use either


store.on('load', function(thisStore, records, options){
// your logic after load goes here
})


or



store.load({
callback: function(records, options, success){
// your logic after load goes here
}
});

loeppky
7 May 2008, 9:37 AM
marvelousgame: glad you figured it out, and thanks for posting the solution.

loeppky
7 May 2008, 3:23 PM
FYI: I will be out of town until 5/17, and thus won't be able to answer any questions until that point.

michaelc
19 Jun 2008, 12:50 PM
Do you have any feel for the difference in your proxy vs the the one here http://extjs.com/forum/showthread.php?t=5586 ?

Same base functionality defined ?
I like yours as it's better documented, that one had one positive a zip file I could pull apart to see the complete model.

loeppky
19 Jun 2008, 1:48 PM
michaelc: I don't have a feel for the one you linked to. I largely ignored it because it was integrating with Spring (which I don't need), and because it wasn't easy to see what was going on just by reading the post. I took the DWRProxy in the thread posted "DWRProxy" and improved it because it was lightweight and easy to understand.

Also, in case you missed it, my second post gives an examples of how to use it.

michaelc
24 Jun 2008, 5:26 PM
my app does seem to run, I took the example grid and modified to use DWR.
when I run the page it throws an error in ext-all.js getJsonAccessor
return obj[expr]; object is undefined.

I expect the issue may be that I did not load parms as I don't need parameters for my process.

any help would be wonderfull


// create the data store
var store = new Ext.data.Store({
proxy: new Ext.ux.data.DWRProxy({
dwrFunction: CompanyList.getCompanyList,
listeners: {
'beforeload': function(dataProxy, params){
}
}
}),
reader: new Ext.data.JsonReader({
root: "data" },
Ext.data.Record.create([
{name: 'company'},
{name: 'price'},
{name: 'change'},
{name: 'pctChange'},
{name: 'lastChange'}

]))
});
store.loadData();

// create the Grid
var grid = new Ext.grid.GridPanel({
store: store,
columns: [
{id:'company',header: "Company", width: 160, sortable: true, dataIndex: 'company'},
{header: "Price", width: 75, sortable: true, renderer: 'usMoney', dataIndex: 'price'},
{header: "Change", width: 75, sortable: true, renderer: change, dataIndex: 'change'},
{header: "% Change", width: 75, sortable: true, renderer: pctChange, dataIndex: 'pctChange'},
{header: "Last Updated", width: 85, sortable: true, renderer: Ext.util.Format.dateRenderer('m/d/Y'), dataIndex: 'lastChange'}
],
stripeRows: true,
autoExpandColumn: 'company',
height:350,
width:600,
title:'Array Grid'
});

grid.render('grid-example');

grid.getSelectionModel().selectFirstRow();


when I run CompanyList.getCompanyList I get a valid result, but I don't think I am even getting to the call it self.


//#DWR-INSERT
//#DWR-REPLY
var s0=new CompanyListObj();var s1=[];var s2=new Company();var s3=new Company();var s4=new Company()

;var s5=new Company();var s6=new Company();var s7=new Company();var s8=new Company();var s9=new Company

();var s10=new Company();var s11=new Company();var s12=new Company();var s13=new Company();var s14=new

Company();var s15=new Company();var s16=new Company();var s17=new Company();var s18=new Company();var

s19=new Company();var s20=new Company();var s21=new Company();var s22=new Company();var s23=new Company

();var s24=new Company();var s25=new Company();var s26=new Company();var s27=new Company();var s28=new

Company();var s29=new Company();var s30=new Company();s0.data=s1;

s1[0]=s2;s1[1]=s3;s1[2]=s4;s1[3]=s5;s1[4]=s6;s1[5]=s7;s1[6]=s8;s1[7]=s9;s1[8]=s10;s1[9]=s11;s1[10]=s12

;s1[11]=s13;s1[12]=s14;s1[13]=s15;s1[14]=s16;s1[15]=s17;s1[16]=s18;s1[17]=s19;s1[18]=s20;s1[19]=s21;s1

[20]=s22;s1[21]=s23;s1[22]=s24;s1[23]=s25;s1[24]=s26;s1[25]=s27;s1[26]=s28;s1[27]=s29;s1[28]=s30;

s2.change="0.02";s2.company="3m Co";s2.lastChange="9/1 12:00am";s2.pctChange="0.03";s2.price="71.72"

;

s3.change="0.42";s3.company="Alcoa Inc";s3.lastChange="9/1 12:00am";s3.pctChange="1.47";s3.price="29

.01";

s4.change="0.28";s4.company="Altria Group Inc";s4.lastChange="9/1 12:00am";s4.pctChange="0.34";s4.price

="83.81";

s5.change="0.01";s5.company="American Express Company";s5.lastChange="9/1 12:00am";s5.pctChange="0.02"

;s5.price="52.55";

s6.change="0.31";s6.company="American International Group Inc.";s6.lastChange="9/1 12:00am";s6.pctChange

="0.49";s6.price="64.13";

s7.change="-0.48";s7.company="AT&T Inc.";s7.lastChange="9/1 12:00am";s7.pctChange="-1.54";s7.price="31

.61";

s8.change="0.53";s8.company="Boeing Co.";s8.lastChange="9/1 12:00am";s8.pctChange="0.71";s8.price="75

.43";

s9.change="0.92";s9.company="Caterpillar Inc.";s9.lastChange="9/1 12:00am";s9.pctChange="1.39";s9.price

="67.27";

s10.change="0.02";s10.company="Citigroup, Inc.";s10.lastChange="9/1 12:00am";s10.pctChange="0.04";s10

.price="49.37";

s11.change="0.51";s11.company="E.I. du Pont de Nemours and Company";s11.lastChange="9/1 12:00am";s11

.pctChange="1.28";s11.price="40.48";

s12.change="-0.43";s12.company="Exxon Mobil Corp";s12.lastChange="9/1 12:00am";s12.pctChange="-0.64"

;s12.price="68.1";

s13.change="-0.08";s13.company="General Electric Company";s13.lastChange="9/1 12:00am";s13.pctChange

="-0.23";s13.price="34.14";

s14.change="1.09";s14.company="General Motors Corporation";s14.lastChange="9/1 12:00am";s14.pctChange

="3.74";s14.price="30.27";

s15.change="-0.03";s15.company="Hewlett-Packard Co.";s15.lastChange="9/1 12:00am";s15.pctChange="-0.08"

;s15.price="36.53";

s16.change="0.05";s16.company="Honeywell Intl Inc";s16.lastChange="9/1 12:00am";s16.pctChange="0.13"

;s16.price="38.77";

s17.change="0.31";s17.company="Intel Corporation";s17.lastChange="9/1 12:00am";s17.pctChange="1.58";s17

.price="19.88";

s18.change="0.44";s18.company="International Business Machines";s18.lastChange="9/1 12:00am";s18.pctChange

="0.54";s18.price="81.41";

s19.change="0.06";s19.company="Johnson & Johnson";s19.lastChange="9/1 12:00am";s19.pctChange="0.09";s19

.price="64.72";

s20.change="0.07";s20.company="JP Morgan & Chase & Co";s20.lastChange="9/1 12:00am";s20.pctChange="0

.15";s20.price="45.73";

s21.change="0.86";s21.company="McDonald\"s Corporation";s21.lastChange="9/1 12:00am";s21.pctChange="2

.40";s21.price="36.76";

s22.change="0.41";s22.company="Merck & Co,Inc.";s22.lastChange="9/1 12:00am";s22.pctChange="1.01";s22

.price="40.96";

s23.change="0.14";s23.company="Microsoft Corporation";s23.lastChange="9/1 12:00am";s23.pctChange="0.54"

;s23.price="25.84";

s24.change="0.4";s24.company="Pfizer Inc";s24.lastChange="9/1 12:00am";s24.pctChange="1.45";s24.price

="27.96";

s25.change="0.26";s25.company="The Coca-Cola Company";s25.lastChange="9/1 12:00am";s25.pctChange="0.58"

;s25.price="45.07";

s26.change="0.35";s26.company="The Home Depot,Inc.";s26.lastChange="9/1 12:00am";s26.pctChange="1.02"

;s26.price="34.64";

s27.change="0.01";s27.company="The Procter & Gamble Company";s27.lastChange="9/1 12:00am";s27.pctChange

="0.02";s27.price="61.91";

s28.change="0.55";s28.company="United Technologies Corporation";s28.lastChange="9/1 12:00am";s28.pctChange

="0.88";s28.price="63.26";

s29.change="0.39";s29.company="Verizon Communications";s29.lastChange="9/1 12:00am";s29.pctChange="1

.11";s29.price="35.57";

s30.change="0.73";s30.company="Wal-Mart Stores, Inc.";s30.lastChange="9/1 12:00am";s30.pctChange="1.63"

;s30.price="45.45";

dwr.engine._remoteHandleCallback('0','0',s0);

java


package org.getahead.dwrdemo.testList;

import org.getahead.dwrdemo.testList.Company;
import org.getahead.dwrdemo.testList.CompanyListObj;


import java.util.ArrayList;
import java.util.List;
public class CompanyList {

public CompanyListObj getCompanyList(){

List<Company> passBack = new ArrayList<Company>();
passBack.add(new Company("3m Co","71.72","0.02","0.03","9/1 12:00am"));
passBack.add(new Company("Alcoa Inc","29.01","0.42","1.47","9/1 12:00am"));
passBack.add(new Company("Altria Group Inc","83.81","0.28","0.34","9/1 12:00am"));
passBack.add(new Company("American Express Company","52.55","0.01","0.02","9/1 12:00am"));
passBack.add(new Company("American International Group Inc.","64.13","0.31","0.49","9/1 12:00am"));
passBack.add(new Company("AT&T Inc.","31.61","-0.48","-1.54","9/1 12:00am"));
passBack.add(new Company("Boeing Co.","75.43","0.53","0.71","9/1 12:00am"));
passBack.add(new Company("Caterpillar Inc.","67.27","0.92","1.39","9/1 12:00am"));
passBack.add(new Company("Citigroup, Inc.","49.37","0.02","0.04","9/1 12:00am"));
passBack.add(new Company("E.I. du Pont de Nemours and Company","40.48","0.51","1.28","9/1 12:00am"));
passBack.add(new Company("Exxon Mobil Corp","68.1","-0.43","-0.64","9/1 12:00am"));
passBack.add(new Company("General Electric Company","34.14","-0.08","-0.23","9/1 12:00am"));
passBack.add(new Company("General Motors Corporation","30.27","1.09","3.74","9/1 12:00am"));
passBack.add(new Company("Hewlett-Packard Co.","36.53","-0.03","-0.08","9/1 12:00am"));
passBack.add(new Company("Honeywell Intl Inc","38.77","0.05","0.13","9/1 12:00am"));
passBack.add(new Company("Intel Corporation","19.88","0.31","1.58","9/1 12:00am"));
passBack.add(new Company("International Business Machines","81.41","0.44","0.54","9/1 12:00am"));
passBack.add(new Company("Johnson & Johnson","64.72","0.06","0.09","9/1 12:00am"));
passBack.add(new Company("JP Morgan & Chase & Co","45.73","0.07","0.15","9/1 12:00am"));
passBack.add(new Company("McDonald\"s Corporation","36.76","0.86","2.40","9/1 12:00am"));
passBack.add(new Company("Merck & Co,Inc.","40.96","0.41","1.01","9/1 12:00am"));
passBack.add(new Company("Microsoft Corporation","25.84","0.14","0.54","9/1 12:00am"));
passBack.add(new Company("Pfizer Inc","27.96","0.4","1.45","9/1 12:00am"));
passBack.add(new Company("The Coca-Cola Company","45.07","0.26","0.58","9/1 12:00am"));
passBack.add(new Company("The Home Depot,Inc.","34.64","0.35","1.02","9/1 12:00am"));
passBack.add(new Company("The Procter & Gamble Company","61.91","0.01","0.02","9/1 12:00am"));
passBack.add(new Company("United Technologies Corporation","63.26","0.55","0.88","9/1 12:00am"));
passBack.add(new Company("Verizon Communications","35.57","0.39","1.11","9/1 12:00am"));
passBack.add(new Company("Wal-Mart Stores, Inc.","45.45","0.73","1.63","9/1 12:00am"));
CompanyListObj data = new CompanyListObj();
data.setData(passBack);
return data;
}

}

fbuckle
25 Jun 2008, 5:01 AM
Try using store.load() instead of store.loadData().

michaelc
25 Jun 2008, 8:34 AM
Try using store.load() instead of store.loadData().

Thank you very much, that it.

tdg2008
6 Jul 2008, 5:50 AM
when i use the code below to call my dwr function , i got a message like "prototype is null or not a Object" in IE8 and "B is undefined "in FireFox3 .
could anybody help me ?


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<script type="text/javascript" src="/ProjectX/dwr/engine.js"></script>
<script type="text/javascript" src="/ProjectX/dwr/util.js"></script>
<script type="text/javascript" src="/ProjectX/dwr/auth.js"></script>
<script type="text/javascript" src="/ProjectX/dwr/interface/pagingGridService.js"></script>
<script type="text/javascript" src="../js/ext-base.js"></script>
<script type="text/javascript" src="../js/ext-all.js"></script>
<script type="text/javascript" src="../js/ext-lang-zh_CN.js"></script>
<script type="text/javascript" src="../js/dwrproxy.js"></script>
<script type="text/javascript">
Ext.onReady(function(){
var store=new Ext.data.Store({
proxy:new Ext.ux.data.DWRProxy({
dwrFunction: pagingGridService.pagingSearch
})
,reader:new Ext.data.XmlReader({
totalRecords: "result",
root:'dataset',
record: "row",
id: "uuid"
})
});
store.load({params:{sql:'AA',start:0, limit:25}});
});

java code :


public String pagingSearch(String sql,int start,int limit){
System.out.println("TDG:"+sql);
System.out.println("TDG:"+start);
System.out.println("TDG:"+limit);
StringBuffer buffer=new StringBuffer();
buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
buffer.append("<dataset>");
buffer.append("<result>"+160+"</result>");
for(int i=start;i<start+limit;i++){
buffer.append("<row>");
buffer.append("<seq>"+i+"</seq>");
buffer.append("<uuid>"+(i+1)+"</uuid>");
buffer.append("<common>Bloodroot"+i+"</common>");
buffer.append("<botanical>Sanguinaria canadensis"+i+"</botanical>");
buffer.append("<zone>4</zone>");
buffer.append("<light>Mostly Shady"+i+"</light>");
buffer.append("<price>"+i+".44</price>");
buffer.append("<avail>03/15/2006</avail>");
buffer.append("<indoor>true</indoor>");
buffer.append("</row>");
}
buffer.append("</dataset>");
return buffer.toString();
}

the code works well in /dwr/test/pagingGridService and also runs after the load metohd call

loeppky
7 Jul 2008, 9:37 AM
tdg2008: It seems like your understanding of DWR is off. You'll usually want DWR to return you an Integer, String, JSON object, or an array of any of the above. As a result, you'll want to use an ArrayReader or a JSONReader. Having your DWR method return an XML string is just odd. Are you sure this is what you want to do?

siddhartha
5 Oct 2008, 8:04 PM
Hi Loeppky,
Could you pls help on this query on the DWRProxy, I am trying to use your DWRProxy version posted on this thread
http://extjs.com/forum/showthread.php?t=49117

Thanks in advance,
Siddhartha

loeppky
7 Oct 2008, 8:23 AM
siddhartha: Response left at http://extjs.com/forum/showthread.php?p=235007#post235007. You basically need to spend a bit of time getting used to DWR first independent of Ext.

fxmisticat
8 Oct 2008, 11:28 AM
I am having a problem with the ArrayReader, no errors.. its populating the grid with empty rows?
it is the same number of rows as I'm returning, so is this a mapping issue?here is what im getting back
//#DWR-REPLY
var s0=new demo();var s1=new demo();var s2=new demo();var s3=new demo();var s4=new
demo();s0.ID="first";s0.displayName="first class";
s1.strID="second";s1.strname="second class";
s2.strID="third";s2.strname="third class";
s3.strID="fourth";s3.strname="fourth class";
s4.strID="fifth";s4.strname="fifth class";
dwr.engine._remoteHandleCallback('0','0',[s0,s1,s2,s3,s4]);

reader: new Ext.data.ArrayReader({},
Ext.data.Record.create([
{name: 'strID',mapping:'id'},
{name: 'strname',mapping:'name'}
]))

columns: [
{id:'id',header: "ID", width: 160, sortable: true, dataIndex: 'id'},
{header: "Name", width: 75, sortable: true, dataIndex: 'name'},
],

fxmisticat
8 Oct 2008, 12:54 PM
even when i try and use jsonreader same thing happens?

loeppky
8 Oct 2008, 3:09 PM
fxmisticat: this isn't a DWRProxy specific issue. As you suggested, this is a problem with how you've configured your reader. An ArrayReader expects an array. A JsonReader expects a JSON object. In your example below, you're proxy is fetching an array of JSON objects, not an array of arrays.

fxmisticat
9 Oct 2008, 4:18 AM
thanks.. i got it working

petujek
18 Nov 2008, 1:43 AM
Hi,
I have problem with binding data to grid. Extjs have response from dwr, but not bind data to grid.

grid item class:


package test.test.chat.entity;

import java.io.Serializable;

public class ChatItem implements Serializable {
protected String chatRoomUuid="";
protected long lineId=0;
protected String sender="";
protected String text="";

public void setChatRoomUuid(String chatRoomUuid) { this.chatRoomUuid = chatRoomUuid; }
public String getChatRoomUuid() { return chatRoomUuid; }
public void setLineId(long lineId) { this.lineId = lineId; }
public long getLineId() { return lineId; }
public void setSender(String sender) { this.sender = sender; }
public String getSender() { return sender; }
public void setText(String text) { this.text = text; }
public String getText() { return text; }
}
dwr service class:


package test.test.chat.services;

import java.util.ArrayList;
import java.util.List;
import test.test.chat.entity.ChatItem;

public class ChatService {
public List<ChatItem> getItems() {
List<ChatItem> chatItemsList = new ArrayList<ChatItem>();
ChatItem item1 = new ChatItem();
item1.setLineId(1);
item1.setChatRoomUuid("test1");
item1.setSender("Pet");
item1.setText("text of test1");
chatItemsList.add(item1);
ChatItem item2 = new ChatItem();
item1.setLineId(2);
item1.setChatRoomUuid("test1");
item1.setSender("PanPoutko");
item1.setText("text of test1");
chatItemsList.add(item2);
return chatItemsList;
}
}
dwr proxy:


* http://extjs.com/forum/showthread.php?t=19529
*/
Ext.namespace("Ext.ux.data");

/**
* @class Ext.ux.data.DWRProxy
* @extends Ext.data.DataProxy
* @author loeppky
* An implementation of Ext.data.DataProxy that uses DWR to make a remote call.
* @constructor
* @param {Object} config A configuration object.
*/
Ext.ux.data.DWRProxy = function(config){
Ext.apply(this, config); // necessary since the superclass doesn't call apply
Ext.ux.data.DWRProxy.superclass.constructor.call(this);
};

Ext.extend(Ext.ux.data.DWRProxy, Ext.data.DataProxy, {

/**
* @cfg {Function} dwrFunction The DWR function for this proxy to call during load.
* Must be set before calling load.
*/
dwrFunction: null,

/**
* @cfg {String} loadArgsKey Defines where in the params object passed to the load method
* that this class should look for arguments to pass to the "dwrFunction".
* The order of arguments passed to a DWR function matters.
* Must be set before calling load.
* See the explanation of the "params" parameter for the load function for further explanation.
*/
loadArgsKey: 'dwrFunctionArgs',

/**
* Load data from the configured "dwrFunction",
* read the data object into a block of Ext.data.Records using the passed {@link Ext.data.DataReader} implementation,
* and process that block using the passed callback.
* @param {Object} params An object containing properties which are to be used for the request to the remote server.
* Params is an Object, but the "DWR function" needs to be called with arguments in order.
* To ensure that one's arguments are passed to their DWR function correctly, a user must either:
* 1. call or know that the load method was called explictly where the "params" argument's properties were added in the order expected by DWR OR
* 2. listen to the "beforeload" event and add a property to params defined by "loadArgsKey" that is an array of the arguments to pass on to DWR.
* If there is no property as defined by "loadArgsKey" within "params", then the whole "params" object will be used as the "loadArgs".
* If there is a property as defined by "loadArgsKey" within "params", then this property will be used as the "loagArgs".
* The "loadArgs" are iterated over to build up the list of arguments to pass to the "dwrFunction".
* @param {Ext.data.DataReader} reader The Reader object which converts the data object into a block of Ext.data.Records.
* @param {Function} callback The function into which to pass the block of Ext.data.Records.
* The function must be passed <ul>
* <li>The Record block object</li>
* <li>The "arg" argument from the load function</li>
* <li>A boolean success indicator</li>
* </ul>
* @param {Object} scope The scope in which to call the callback
* @param {Object} arg An optional argument which is passed to the callback as its second parameter.
*/
load: function(params, reader, loadCallback, scope, arg){
var dataProxy = this;
if (dataProxy.fireEvent("beforeload", dataProxy, params) !== false) {
var loadArgs = params[this.loadArgsKey] || params; // the Array or Object to build up the "dwrFunctionArgs"
var dwrFunctionArgs = []; // the arguments that will be passed to the dwrFunction
if (loadArgs instanceof Array) {
// Note: can't do a foreach loop over arrays because Ext added the "remove" method to Array's prototype.
// This "remove" method gets added as an argument unless we explictly use numeric indexes.
for (var i = 0; i < loadArgs.length; i++) {
dwrFunctionArgs.push(loadArgs[i]);
}
} else { // loadArgs should be an Object
for (var loadArgName in loadArgs) {
dwrFunctionArgs.push(loadArgs[loadArgName]);
}
}
dwrFunctionArgs.push({
callback: function(response){
// call readRecords verses read because read will attempt to decode the JSON,
// but as this point DWR has already decoded the JSON.
var records = reader.readRecords(response);
dataProxy.fireEvent("load", dataProxy, response, loadCallback);
loadCallback.call(scope, records, arg, true);
},
exceptionHandler: function(message, exception){
// the event is supposed to pass the response, but since DWR doesn't provide that to us, we pass the message.
dataProxy.fireEvent("loadexception", dataProxy, message, loadCallback, exception);
loadCallback.call(scope, null, arg, false);
}
});
this.dwrFunction.apply(Object, dwrFunctionArgs); // the scope for calling the dwrFunction doesn't matter, so we simply set it to Object.
} else { // the beforeload event was vetoed
callback.call(scope || this, null, arg, false);
}
}
});
grid creation js:


/**
* Application Layout
* by Jozef Sakalos, aka Saki
* http://extjs.com/learn/Tutorial:Application_Layout_for_Beginners
*/

// reference local blank image
Ext.BLANK_IMAGE_URL = "/dwrextjs/ext2js/resources/images/default/s.gif";

// create namespace
Ext.namespace('myNameSpace');

// Just to allow this tutorial to work for 1.1 and 2.
Ext.Ext2 = (Ext.version && (Ext.version.indexOf("2") == 0));

var GridUI = function() {
var ds = new Ext.data.Store({
proxy: new Ext.ux.data.DWRProxy({
dwrFunction: ChatService.getItems,
listeners: {
'beforeload': function(dataProxy, params){
params[dataProxy.loadArgsKey] = ['query'];
}
}
}),
reader: new Ext.data.JsonReader({ }, Ext.data.Record.create([
{ name: "lineId", type: "String"},
{ name: "sender", type: "String"},
{ name: "text", type: "String"}
]))

});
ds.load();

var grid = new Ext.grid.GridPanel({
el: "mygrid",
autoScroll: true,
autoHeight: true,
autoWidth: true,
ds: ds,
cm: new Ext.grid.ColumnModel([
{ header: 'lineId', dataIndex: 'lineId', width: 250, sortable: true },
{ header: 'sender', dataIndex: 'sender', width: 250, sortable: true },
{ header: 'text', dataIndex: 'text', width: 250, sortable: true }
]),
sm: new Ext.grid.RowSelectionModel({
singleSelect: true,
listeners: {
rowselect: function(smObj, rowIndex, record) {
selRecordStore = record;
}
}
}),
autoSizeColumns: true,
trackMouseOver: true,
tbar: [ new Ext.Toolbar.Button({
text: 'Add', handler: function(){
//Load New Form
alert("add item");
}
}), new Ext.Toolbar.Button({
text: 'Edit', handler: function(){
//Load New Form
//Load Data
form.loadRecord(selRecordStore);
}
}), new Ext.Toolbar.Button({
text: 'Delete', handler: function(){
//Call for Delete for the record with this identifier
var id = selRecordStore["field1"]
}
})],
bbar: new Ext.PagingToolbar({
pageSize: 10,
store: ds,
displayInfo: true,
displayMsg: "Displaying Records {0} - {1} of {2}",
emptyMsg: "No Records to display",
items: ['-']
})
});



return {
init : function() {
grid.render();
}, getStore: function() {
return ds;
}
}
}();

Ext.onReady(GridUI.init, GridUI, true);
dwr response in firebug:


//#DWR-INSERT

//#DWR-REPLY

var s0={};var s1={};s0.chatRoomUuid="test1";s0.lineId=2;s0.sender="PanPoutko";s0.text="text of test1"

;

s1.chatRoomUuid="";s1.lineId=0;s1.sender="";s1.text="";

dwr.engine._remoteHandleCallback('0','0',[s0,s1]);

sean.zhou
18 Nov 2008, 10:04 AM
In other DataProxy implementation, there is abort() to abort an ongoing ajax call. How to add this method to the DWRProxy?:-?

loeppky
18 Nov 2008, 2:09 PM
petujek: a JsonReader is expecting an Object that has two properties: a total property and a root property which where the array of JSON objects are. See http://extjs.com/deploy/dev/docs/?class=Ext.data.JsonReader. Your DWR call is just returning an array of objects. It's not including the wrapping Object.

loeppky
18 Nov 2008, 2:10 PM
sean.zhou: this would be very dependent on how you cancel requests in DWR. It's been over 6 months since I looked, but when I did, I couldn't find the ability to abort a request in DWR. If you find it, let me know, and we can see about updating the code.

petujek
19 Nov 2008, 3:08 AM
Hi,
problem was at grid creation js:

sending params to method:


proxy: new Ext.ux.data.DWRProxy({
dwrFunction: ChatService.getItems,
listeners: {
'beforeload': function(dataProxy, params){
// params[dataProxy.loadArgsKey] = ['query'];
params[dataProxy.loadArgsKey] = [];
}
}
}),


At reader I set type to String instead string. True is string:


reader: new Ext.data.JsonReader({ }, Ext.data.Record.create([
{ name: "lineId", type: "string"},
{ name: "sender", type: "string"},
{ name: "text", type: "string"}
]))


loeppky: total property and root property are optional. This use is functional.

I create small demo. At last two weeks I place it to web.

fxmisticat
16 Jan 2009, 4:17 PM
Loeppky - how are things going? I have a question.. I have run been passing objects that i am exposing via dwr put have only been passing them back using the actually proxy js functions that dwr creates.

Do you think it is possible to modify dwrproxy to pass objects instead of parameters?

ie: submitting a form pass a form object vs all the name/value pairs?

this has worked for me since i am using a messaging bus and the server sends the client an object and my controls are subscribed to the typeOf (which comes across as the function name).

thoughts?

mahendra_gayatri
29 Jan 2009, 4:17 AM
Hi,

I have my ExtJS developed application with PHP deployed in my XAMPP server.
Now, I have a requirement to interact with DWR (possibly using DWRproxy), and since that has to be deployed in a WAR file, i had to install tomcat plugin for XAMPP.

Problem : If I continue with my application as it is, I need to request for the dwrFile.war with URL localhost:8080/dwrFile/myFnc
This throws the nasty "cannot access" error, as we need to do a relative path.

Is there any workaround for this?
or
Has can anyone pls point me to the post/example where the complete setup is explained.

Thx for ur time.

Takashi MIYATA
2 Mar 2009, 5:52 PM
Hello loeppky,

I'm interested in DWRProxy.
What kind of licence are you granting for your code?

Best regards

loeppky
6 Mar 2009, 10:42 AM
Hi guys,

Sorry for the delayed response on my end. I recently moved, and am just getting back into checking the Ext forums regularly. Concerning licensing, please use the code however you like. If you're making a commercial product, it should be documented that one can get DWRProxy from this site.

Steve

rtikku
24 Mar 2009, 11:41 PM
Hi Loeppky,

Thanks for the DWRProxy extn. I have been using it in my dev env for some time now and it is working great. However, now I have the following requirement.

My page contain one or more grids. Each of the grids have a Refresh option in its context menu that refreshes that particular grid. This works fine, however, if a grid is refreshed using the rightclick when the http session has expired, it continuously displays the "Loading" mask and does not process the json returned by the server.

The json I return when the session has expired is

{success:false, error:true, errorMessage:'Not Logged on. Please Login again.'}

I tried to listen for loadexception on my store, but that was not getting called.

Any clues on how to handle this would be greatly appreciated.

Thanks again.

NickeJ
16 Apr 2009, 11:49 PM
Hi Loeppky
Thanks for this extension! I just tried it with Ext 3 RC1 and it doesn't work due to changes in the Ext.data.DataProxy class. To make it work again i had to add the following snippet to the constructor (have a look at Ext.data.HttpProxy):

this.api = {
load: undefined,
save: undefined,
create: undefined,
destroy: undefined
};
I also noted that Ext.data.DataProxy.doRequest(..) is deprecated as of Ext 3.

Cheers Niklas

loeppky
21 Apr 2009, 8:46 AM
Hi NicieJ,

Thanks for the info about Ext 3. I have been doing so much backend work the last 6 months, that Ext has unfortunately been off my radar for a bit. I will aim to look into this by the end of the week, and maybe start a new thread for the Ext 3 version.

Thanks,
Steve

loeppky
20 May 2009, 7:39 PM
I know I said I would do this a few weeks ago, but I have been swamped with work. I'm blocking some time out of work on Thursday or Friday to take care of this. I'll also work to get the code posted on GitHub.

loeppky
24 May 2009, 1:15 PM
As stated on the original post:

DwrProxy is now part of a larger ExtJsWithDwr project on GitHub (http://github.com/BigLep/ExtJsWithDwr/) (see form post (http://extjs.com/forum/showthread.php?t=69349)).


What does this mean?

DWRProxy has been renamed to DwrProxy (although DWRProxy) is provided for backwards compatibility.
The code is publically available and easy to check out.
Official examples have been created that demonstrate DwrProxy in action. They're part of the GitHub project or can be seen here: http://biglep.s156.eatj.com/extJsWithDwrExamples/.
Now that all this overhead is taken care for DwrProxy, work on Ext 3.x support will come next week.



Where can I find the code?
http://github.com/BigLep/ExtJsWithDwr/blob/v2/source/data/DwrProxy.js

NickeJ
11 Jun 2009, 6:46 AM
Hi again!
More changes are needed to make it work with Ext3 rc2 I applied the workaround from this thread to make it work http://extjs.com/forum/showthread.php?t=70251

Cheers Niklas

loeppky
14 Jun 2009, 9:12 AM
Nicklas,

Thanks for the info. I am working today on making DwrProxy work with Ext 3, and will post my code to the ExtJsWithDwr project on GitHub.

Thanks,
Steve

loeppky
14 Jun 2009, 10:46 AM
As discussed in http://extjs.com/forum/showthread.php?p=343185, Ext 3.x support for Ext.ux.data.DwrProxy has been added and checked in. Please post all comments, questions, and/or issues for using Ext.ux.data.DwrProxy in the new thread.

Relevant links:

v3 branch of ExtJsWithDwr (http://github.com/BigLep/ExtJsWithDwr/tree/v3)
Ext.ux.data.DwrProxy code for ExtJS 3.x (http://github.com/BigLep/ExtJsWithDwr/blob/v3/source/data/DwrProxy.js)

NickeJ
14 Jun 2009, 9:41 PM
Great I'll give it a try today.
Thanks,
Niklas

ushangar
18 Jun 2009, 8:18 AM
Hi,
First of all thank you for this extension. I have tried to use it in one of the Charity Origination application I am working on during my free time and I got it to work.
Although it was a bit of learning curve at first, once it was off the ground, it worked as expected.
I need some help on one more thing to complete my POC. How can I pass a Javascript object back to the DWR Java service at backend?
I have a Member list grid and I also have search panel, I like to pass a JavaScript object called “SearchCriteriaBean” .
I have seen examples of String and long being passed as Java arguments.

loeppky
19 Jun 2009, 6:34 AM
ushangar: Is this concerning Ext 3 or 2? This is the forum post for Ext 2.

mask_hot
6 Jul 2009, 7:07 AM
Hi,

I'm trying to do a POC of Extjs in a Liferay + Sping project.

I'm not familiar with DWR but I have some experience with ExtJS.

As the github is quite not reachable, I'd like to have a how to to use the dwrProxy.

Is there a full project sample available?

thanks a lot.

Linkrjr
1 Sep 2009, 12:30 AM
HI all,

I am having problems to get the beforeload listeners to work.

I have the code below defined but somehow DwrProxy is firing a beforeload method because I am getting the expected result back but it is sending NULL as parameter to my remote method.

A little digging around I found out that it apparently is called the DataProxy Parent beforeload listener which I assume to be empty at that point, reason why my remote method end up with a NULL parameter.

Am I doing anything wrong here?



var users = new Ext.data.Store({
proxy: new Ext.ux.data.DwrProxy({
dwrFunction: UserInterface.getData,
listeners: {

'beforeload': function(dataProxy, params){

alert(dataProxy.loadArgsKey);

params[dataProxy.loadArgsKey] = {
"name":"Test"
};

},

scope: this

}
}),
reader: new Ext.data.JsonReader({
root: 'rows'
}, Ext.data.Record.create([
{name:'name'}
]))
});

Linkrjr
1 Sep 2009, 5:23 AM
Ok, I have found the problem here, I was using ExtJS3.x and the DwrProxy v2.
I have swapped extjs3.0 with 2.x and everything worked.

I have tested extjs3.0 with the new DwrProxy v3 and it works fine as well.

Thanks.

crazy44
21 Oct 2009, 12:58 PM
HI, I have an error on this line :


throw new Exception('"action" is not defined.');\n

Exception is not defined

Did I miss an import ?

thanks

loeppky
22 Oct 2009, 9:27 AM
It sounds like you're using Ext 3. If that's the case, go to http://www.extjs.com/forum/showthread.php?p=343185.

orangejs
11 Jun 2010, 5:45 AM
Hi, I have a program, I could see the data is returned from the server, and store is loaded with the data. But I still could not see the data in the grid. Any hint or guess? Below is my simplified test case (which still doesn't work). Thanks a lot.


var programDataStore = new Ext.data.JsonStore({

proxy:new Ext.ux.data.DwrProxy({
dwrFunction: ProgramFileDwr.getAllFiles
}),

reader: new Ext.data.JsonReader({
root : 'objectsToConvertToRecords'
}, [
'name',
'department'
])

programDataStore.load();


var grid = new Ext.grid.GridPanel({
store: programDataStore ,
columns:
{header: "name", width: 75, dataIndex: 'name', sortable: true },
{header: "department", width: 75, dataIndex: 'department', sortable: true}

orangejs
13 Jun 2010, 9:19 PM
This problem is because the index filed doesn't match the json field (with uppercase in index field). The DwrProxy is working great. Thanks.


Hi, I have a program, I could see the data is returned from the server, and store is loaded with the data. But I still could not see the data in the grid. Any hint or guess? Below is my simplified test case (which still doesn't work). Thanks a lot.


var programDataStore = new Ext.data.JsonStore({

proxy:new Ext.ux.data.DwrProxy({
dwrFunction: ProgramFileDwr.getAllFiles
}),

reader: new Ext.data.JsonReader({
root : 'objectsToConvertToRecords'
}, [
'name',
'department'
])

programDataStore.load();


var grid = new Ext.grid.GridPanel({
store: programDataStore ,
columns:
{header: "name", width: 75, dataIndex: 'name', sortable: true },
{header: "department", width: 75, dataIndex: 'department', sortable: true}

Fox
21 Sep 2010, 10:03 AM
Hi - I'm trying to figure out how to use this component, but the examples link is dead:
http://biglep.s156.eatj.com/extJsWithDwrExamples/

I'm having problems downloading the source as well - the download starts but never appears to end:
http://github.com/BigLep/ExtJsWithDwr

Thanks

Praveen Adivi
28 Oct 2010, 7:44 AM
Hi guys I am trying to use server side sorting with Java, extjs and DWR and I was wondering if there were any examples that I can look at to get this functionality working

softwareengineer
24 Jan 2011, 5:56 AM
Hi loeppky (http://www.sencha.com/forum/member.php?4389-loeppky),
Can you please guide me to get the extjs grid filter passing parameter / values to server side.

I would appreciate if you can guide me ASAP.
Thank you,