PDA

View Full Version : Encoding form fields into JSON object graph



Ranma13
5 Mar 2010, 5:17 PM
I have some form fields where the name is like so:


var clientInfo = {
xtype: 'fieldset',
items:
[
{
fieldLabel: 'First Name',
name: 'Client.FirstName'
},
{
fieldLabel: 'Last Name',
name: 'Client.LastName'
}
]
};What I want to do is encode this to a JSON object graph. Using Ext.util.JSON.encode(), it encodes to:


"Client.FirstName" : "John",
"Client.LastName" : "Doe"However, I need it to be in the form:


"Client" : { "FirstName" : "John", "LastName" : "Doe" }

Does anyone know how I can achieve this?

tomtom-
6 Mar 2010, 1:05 PM
Hi Ranma13,

You can do this :


var client = {};
client["FirstName"] = "John";
client["LastName"] = "Doe";

var JsonClientInfo = {};
JsonClientInfo["client"] = client;

Ext.encode(JsonClientInfo);

Ranma13
6 Mar 2010, 1:07 PM
Hmm, thanks. I was hoping there would be an easier way to do it since I have over 50 fields and 5 child objects in one form. Any other suggestions would be greatly appreciated.

ZeusTheTrueGod
6 Mar 2010, 10:26 PM
That is realy easy. I've done it in all my projects.



Ext.ux.FormHelper = (function(){
return {

init:function(){
return this;
}

//returns a object representing the
//form values. it moves around all child items
//which have 'getValue' function and fills object with their name
,getValues:function(form){
var items = form.findBy(function(item){
return typeof item.getValue == 'function'
});
var obj = {}
Ext.each(items,function(item){
obj[item.name] = item.getValue();
});
return obj;
}
}//function
)().init();


you can call Ext.ux.FormHelper.getValues(panel) where panel is a container for your fields.
note for beginner: don't call Ext.ux.FormHelper.getValues(clientInfo) because clientInfo is just a config, not a real panel.

write me private message if that doesn't work or if you need some help, may be I could assist somehow

tomtom-
7 Mar 2010, 2:20 AM
Hi Ranma13,

I gave you a way to get the syntax you want. Now you have to automate it according to your context like ZeusTheTrueGod wrote you.

Bye