PDA

View Full Version : Grid not populated with records



sachintaware
13 Mar 2012, 5:09 AM
Hello
My issue is related to extjs 3.4 but I don't think we have a separate discussion board for that.
I am not able to display the records in the grid.All I get is a empty grid,but on the console i can see the json returned correctly.
Extjs file:



Ext.onReady(function(){

Ext.BLANK_IMAGE_URL = '/StaffingApplication/ext-3.2.1/resources/images/default/s.gif';

var Contact = Ext.data.Record.create([
{name: 'id'},
{
name: 'firstName',
type: 'string'
},{
name: 'lastName',
type: 'string'
},{
name: 'email',
type: 'string'
},{
name:'statusTitle',
type:'string'
},{
name:'clientName',
type:'string'
},{
name:'reqTitle',
type:'string'
}]);

var proxy = new Ext.data.HttpProxy({
api: {
read :'candidates/view.action'
}
});

var reader = new Ext.data.JsonReader({
totalProperty: 'total',
successProperty: 'success',
idProperty: 'id',
root: 'data',
messageProperty: 'message' // <-- New "messageProperty" meta-data
},
Contact);

// The new DataWriter component.
var writer = new Ext.data.JsonWriter({
encode: true,
writeAllFields: true
});

// Typical Store collecting the Proxy, Reader and Writer together.
var store = new Ext.data.Store({
id: 'user',
proxy: proxy,
reader: reader,
writer: writer, // <-- plug a DataWriter into the store just as you would a Reader
autoSave: false // <-- false would delay executing create, update, destroy requests until specifically told to do so with some [save] buton.

});

//read the data from simple array
store.load();
var rec1 = store.getById(1);
console.log(rec1);

Ext.data.DataProxy.addListener('exception', function(proxy, type, action, options, res) {
Ext.Msg.show({
title: 'ERROR',
msg: res.message,
icon: Ext.MessageBox.ERROR,
buttons: Ext.Msg.OK
});
});


/* var editor = new Ext.ux.grid.RowEditor({
saveText: 'Update'
});*/


// create grid
var grid = new Ext.grid.GridPanel({
store: store,
columns: [
{header: "FIRSTNAME",
width: 150,
sortable: true,
dataIndex: 'firstName',
/*editor: {
xtype: 'textfield',
allowBlank: false
}*/},
{header: "LASTNAME",
width: 150,
sortable: true,
dataIndex: 'lastName',
/* editor: {
xtype: 'textfield',
allowBlank: false
}*/},
/*{header: "PHONE #",
width: 160,
sortable: true,
dataIndex: 'phone',
editor: {
xtype: 'textfield',
allowBlank: false
}}*/
{header: "EMAIL",
width: 150,
sortable: true,
dataIndex: 'email',
/*editor: {
xtype: 'textfield',
allowBlank: false
}*/},
{header: "STATUS",
width: 150,
sortable: true,
dataIndex: 'statusTitle',
/* editor: {
xtype: 'textfield',
allowBlank: false
}*/},
{header: "CLIENTNAME",
width: 150,
sortable: true,
dataIndex: 'clientName',
/*editor: {
xtype: 'textfield',
allowBlank: false
}*/},
{header: "REQUIREMENT",
width: 150,
sortable: true,
dataIndex: 'reqTitle',
/* editor: {
xtype: 'textfield',
allowBlank: false
}*/}
],
viewConfig:{forcefit:true},
//plugins: [editor],
title: 'Candidates',
height:500,
width:900,
frame:true,
/*tbar: [{
iconCls: 'icon-user-add',
text: 'Add Contact',
handler: function(){
var e = new Contact({
name: 'New Guy',
phone: '(000) 000-0000',
email: 'new@loianetest.com',
contact_address:'Street,State'
});
editor.stopEditing();
store.insert(0, e);
grid.getView().refresh();
grid.getSelectionModel().selectRow(0);
editor.startEditing(0);
}
},{
iconCls: 'icon-user-delete',
text: 'Remove Contact',
handler: function(){
editor.stopEditing();
var s = grid.getSelectionModel().getSelections();
for(var i = 0, r; r = s[i]; i++){
store.remove(r);
}
}
},{
iconCls: 'icon-user-save',
text: 'Save All Modifications',
handler: function(){
store.save();
}
}]*/
});

//render to DIV
grid.render('crud-grid');
});



When I try to do a console.log(store.getbyid(1)) i get undefined on the console.I am not able to figure out the issue as no error is displayed.

Please guide me through this.

Thanks
Sach

chramer
13 Mar 2012, 5:58 AM
not sure, but looking at my ext3 projects, i have

var Contact = new Ext.data.Record.create([

sachintaware
13 Mar 2012, 9:00 PM
Thanks Chramer,tried it but did not work!! :(

chramer
14 Mar 2012, 12:02 AM
store lode is asynchronous.. so this should work!


store.load({
callback : function() {
var rec1 = store.getById(1);
console.log(rec1);
}
});


is it ?

sachintaware
14 Mar 2012, 12:19 AM
No Chramer no luck still!!!
still getting "undefined" in the console.


Thanks
Sach

chramer
14 Mar 2012, 12:26 AM
are you sure you have a record with id=1 ?

sachintaware
14 Mar 2012, 12:51 AM
Thank you for proving I am stupid Chramer ;)
Actually i am not sure how the id's are assigned?(internally by the store is what i assumed) and hence searched for id=1.

ButI also added


console.log(store.getCount());

and it gives me the correct total as 7668 confirmed as the count of JSON records is same.
But if the store has the records why the grid is not displaying them??

Thanks
sach

chramer
14 Mar 2012, 12:56 AM
do you see the grid, the headers ?
try to comment this line

render : Ext.getBody()
from the grid config

sachintaware
14 Mar 2012, 1:20 AM
Yes,i see the grid and the headers.Also,the scroll bar but the records are not visible. :P
I don't have the above line in my congfig.

Thanks
Sach

chramer
14 Mar 2012, 1:32 AM
i just added this to your code

new Ext.Window({
width : 400,
height : 500,
items : [grid],
}).show();
and it works..

32716
pay attention here :

grid.render('crud-grid');
what do you have in 'crud-grid' ?
did you set the layout for 'crud-grid', like
layout : 'fit' or something else ?

sachintaware
14 Mar 2012, 1:43 AM
No i haven't set any layout for


grid.render('crud-grid');


Its just a div in my jsp page.


<html>
<head>
<title></title>

<!-- ExtJS css -->
<link rel="stylesheet" type="text/css" href="/StaffingApplication/ext-3.2.1/resources/css/ext-all.css" />

<!-- Row Editor plugin css -->
<!-- <link rel="stylesheet" type="text/css" href="/StaffingApplication/ext-3.2.1/examples/ux/css/rowEditorCustom.css" />-->
<link rel="stylesheet" type="text/css" href="/StaffingApplication/ext-3.2.1/examples/shared/examples.css" />
<link rel="stylesheet" type="text/css" href="/StaffingApplication/ext-3.2.1/examples/ux/css/RowEditor.css" />

<!-- App custom css -->
<link rel="stylesheet" type="text/css" href="/StaffingApplication/css/crudgrid.css" />

<!-- ExtJS js -->
<script src="/StaffingApplication/ext-3.2.1/adapter/ext/ext-base.js"></script>
<script src="/StaffingApplication/ext-3.2.1/ext-all.js"></script>

<!-- Row Editor plugin js -->
<script src="/StaffingApplication/ext-3.2.1/examples/ux/RowEditor.js"></script>

<!-- App js -->
<script src="/StaffingApplication/js/crud-grid.js"></script>

</head>
<body>
<div id="crud-grid"></div>
</body>
</html>


Do I need to add a layout??

chramer
14 Mar 2012, 1:58 AM
oo .. it is div! didn't noticed that
no, you don't need a layout for div..
but it also works for me with the div :)
we need a "third eye" here...

checked in IE, Firefox, Chrome with ext 3.4.0 - works fine

sachintaware
14 Mar 2012, 2:12 AM
:> Ha ha ..good one!!
I wonder how i could resolve it!!!
Ya i checked it in chrome,not IE but same issue. I am not sure but could the Json be the culprit?
I get it as



{"data":[[29,"Vikram","","bj.vikra@gmail.com","Shortlisted","HireCraft","Support Engineer"],[39,"Anchal","Chauhan","ariesanchl@gmail.com","Scheduled","HireCraft","Support Engineer"],
[40,"Vivek","","vivek.kodanca@gmail.com","Shortlisted","HireCraft","Support Engineer"]],"total":7668,"success":true}

I mean is the name: "value" pairing mandatory??
I directly get the values.

Thanks

sachintaware
14 Mar 2012, 4:50 AM
Hello Chramer,I think i got the problem[not the solution yet ;) ]

My scenario is ,I use hibernate for fetching the records from DB.Now i have used a join to fetch the results and they are returned as follows.These are from 3 different tables and hence looks as a nested json



[
{
"id": 1984,
"reqid": 158,
"statusTitle": "Pending"
},
{
"id": 20514,
"firstName": "Manish",
"lastName": "Harwani",
"email": "mrharwani1@rediffmail.com"
},
{
"id": 158,
"client": {
"id": 15,
"clientName": "Emerson"
},
"clientId": 15,
"reqTitle": "Financial Analyst"
}
],
[
{
"id": 1985,
"reqid": 158,
"statusTitle": "Pending"
},
{
"id": 20515,
"firstName": "Rashmikanta",
"lastName": "Swain",
"email": "rkswain@gmail.com"
},
{
"id": 158,
"client": {
"id": 15,
"clientName": "Emerson"
},
"clientId": 15,
"reqTitle": "Financial Analyst"
}
],
[
{
"id": 1986,
"reqid": 158,
"statusTitle": "Pending"
},
{
"id": 20516,
"firstName": "Debtanu",
"lastName": "Chakraborty",
"email": "debtanu.c@rediffmail.com"
},
{
"id": 158,
"client": {
"id": 15,
"clientName": "Emerson"
},
"clientId": 15,
"reqTitle": "Financial Analyst"
}
]


Now when I fetch records from a single table,i.e only 2-3 columns in the grid,they are displayed in the grid.
But,this isn't.How can I convert this into a plain single json record without the internal nesting?

chramer
14 Mar 2012, 5:12 AM
ok! I think you should handle this on the hibernate side..
zero hibernate knowledge here :)
I'll try to figure an Ext way.. but it will be nasty!

sachintaware
14 Mar 2012, 5:46 AM
Ya if possible please post it.

Thanks for the help and guidance.

Sach

börn
14 Mar 2012, 11:54 AM
You can achieve this on two ways. First as mentioned you can do that with ext by mapping the nested data to fields you want to display as columns in your grid. See the fields docu and especially the mapping config. The disadvantage is, that you may send too much data in your request you don't want to display.

The other way you would build a transfer object or view helper class containing the flat data you want to display I.e. send as Json. You may also put your data into a hashmap or you use a mapping framework like dozer to convert your beans from hibernate objects to transfer objects.

If you use Jackson and the hibernate module as I mentioned before you may collect only those data you want to display in your controller by explicitly initializing your lazy collection and then returning your object with @ResponseBody then the Jackson hibernate module would ignore the uninitialized properties and won't serialize them to Json.

Happy coding...

sachintaware
14 Mar 2012, 11:53 PM
@born

Hello
After some study I learnt that the nested JSON issue can be resolved using the @JsonUnwrapped
annotation.
I tried to add it to my model pojo's



private int id;
private String firstName;
private String lastName;
private String email;

@JsonUnwrapped
private Set<CandidateStatus> candidateStats = new HashSet<CandidateStatus>(0);

@OneToMany //(mappedBy="candidate")
@Fetch(FetchMode.JOIN)
@JoinColumn(name="ResID",nullable=false,referencedColumnName="RID")
@JsonIgnore
public Set<CandidateStatus> getCandidateStats() {
return candidateStats;
}
public void setCandidateStats(Set<CandidateStatus> candidateStats) {
this.candidateStats = candidateStats;
}

and


public class CandidateStatus{

private int id;
private String statusTitle;
@JsonUnwrapped
private Candidates candidate;
private int reqid;

@JsonUnwrapped
private Requirements requirement;

@ManyToOne
@Fetch(FetchMode.JOIN)
@JoinColumn(name="ReqID",insertable=false,updatable=false)
@JsonIgnore
public Requirements getRequirement() {
return requirement;
}

This is done at property level as it does not support class level declaration.
But I am still getting the same nested json.Now,it works when,



Value is serialized as JSON Object
Serialization is done using BeanSerializer, not a custom serializer
No type information is added; if type information needs to be added, structure can not be altered regardless of inclusion strategy; so annotation is basically ignored.


As I am using Jackson it uses BeanSerializer(I suppose),so what is the mistake I am committing?
I went through these threads as they said this has been sorted in the jackson release 1.9.
http://jackson.codehaus.org/1.9.0/javadoc/org/codehaus/jackson/annotate/JsonUnwrapped.html
and
http://www.cowtowncoder.com/blog/archives/2011/10/entry_463.html

Thanks
Sach

sachintaware
15 Mar 2012, 1:52 AM
@Chramer
You seem to have posted a extjs solution to this(I got an email notification about it),but not visible here on the thread. :P
I am not sure why?:-/

Thanks
Sach

börn
15 Mar 2012, 3:00 AM
don't know about the unwrapping annotation - haven't use it so far. I normally have more than one issue for using the domain class in a client. Sometimes you have to display some domain class in a grid view, sometimes you want to edit the fields. If you declare your domain class with this annotation you will always get the unwrapped values? If you want to edit only the candidate status in a editor later this would be messy again...

so you should consider some value helper object or you use a store with a mapping attribute or you use extjs4 where you have a more sophisticated model system, so you can declare models with sub-models (hasMany) associations and so on.

sachintaware
15 Mar 2012, 3:08 AM
@born
You said


If you use Jackson and the hibernate module as I mentioned before you may collect only those data you want to display in your controller by explicitly initializing your lazy collection and then returning your object with @ResponseBody


Now,I do use jackson and to get specific records I wrote a HQL like this


public List<CandidateStatus> getcandidateStatus() {

return hibernateTemplate.find("select candstat.candidate.firstName as firstName,candstat.candidate.lastName as lastName,candstat.candidate.email as email,candstat.statusTitle as statusTitle,candstat.requirement.client.clientName as clientName,candstat.requirement.reqTitle as reqTitle from CandidateStatus as candstat inner join candstat.candidate as candidate inner join candstat.requirement as requirement");

}


selecting specific data or columns.In the controller and service layer.
Controller:


public @ResponseBody Map<String,? extends Object> view() throws Exception {

try{
//List<Candidates> candidates = candidatesService.getCandidatesList();
List<CandidateStatus> candidatestatus = candidatesService.getCandidateStatusList();
return getMap(candidatestatus);



Service:


public List<CandidateStatus> getCandidateStatusList()
{
//return candidatesDAO.getCandidates();
return candidatesDAO.getcandidateStatus();
}


But with this query the Json I get is in this format


{
"data": [
[
29,
"Vikram",
"",
"bj.vikra@gmail.com",
"Shortlisted",
"HireCraft",
"Support Engineer"
],
[
39,
"Anchal",
"Chauhan",
"ariesanchl@gmail.com",
"Scheduled",
"HireCraft",
"Support Engineer"
],
[
40,
"Vivek",
"",
"vivek.kodanca@gmail.com",
"Shortlisted",
"HireCraft",
"Support Engineer"
]
],
"total": 7668,
"success": true
}

Only values....not the standard "name"=value pair form.How can bring it to the standard form?


Otherwise,if I use this query,without a select


public List<CandidateStatus> getcandidateStatus() {
return hibernateTemplate.find("from CandidateStatus candstat inner join candstat.candidate as candidate");

}

the JSON returned is this


{
"data": [
[
{
"id": 29,
"reqid": 27,
"statusTitle": "Shortlisted"
},
{
"id": 45,
"firstName": "Vikram",
"lastName": "",
"email": "bj.vikram@gmail.com"
}
],
[
{
"id": 71,
"reqid": 33,
"statusTitle": "Pending"
},
{
"id": 45,
"firstName": "Vikram",
"lastName": "",
"email": "bj.vikram@gmail.com"
}
]
],
"total": 7668,
"success": true
}

nested and with the "name"=value format.Any mistake in the query and also how to solve the nesting issue?