How to send model specific attributes to server side in extjs4? - json

I am working in extjs4 MVC structure and I have been facing problem in extjs4
all the fields are submitting to server side but I want to send only some fileds of model class to server side. How can I get this output?
1) Here is my model class
Ext.define('ab.model.sn.UserModel',{
extend: 'Ext.data.Model',
//idproperty:'userId',//fields property first position pk.
fields: ['userId','firstName','middleName','lastName','languageId','primaryEmail','birthDate','password','securityQuestionId','securityQuestionAnswer','isMale','creationTime','ipAddress','confirmationCode','userStatusId',],
proxy:
{
type:'ajax',
//type:'localstorage',
//id:'users',
api:
{
read:'http://localhost/balaee/Balaee/index.php/SocialNetworking/user/AuthenticateLogin',
create:'http://localhost/balaee/Balaee/index.php/SocialNetworking/user/AuthenticateLogin122',
update:'http://localhost/balaee/Balaee/index.php/SocialNetworking/user/AuthenticateLogin123'
},//end of api
reader:
{
type:'json',
},//end of reader
writer:
{
type:'json',
root:'records',
},//End of writer
}//end of proxy
});
2) Here is my some controller file code
var userObject = Ext.ModelManager.create(
{
firstName:record.get('firstName'),
password:record.get('password'),
},'ab.model.sn.UserModel');
userObject.save({
success: function(record, operation)
{
console.log("registration successssssssssss "+record.get('userId'));
},//End of success function
failure: function(record, operation)
{
console.log("Inside failure functionnnnn");
},//End of failure function
callback: function(record, operation)
{
console.log("Inside callback functionnnnnn");
}//End of callback function
});// End of check save function
3) And data would be going in json format
{"records":{"userId":"","firstName":"ram","middleName":"","lastName":"","languageId":"","primaryEmail":"","birthDate":"","password":"sham","securityQuestionId":"","securityQuestionAnswer":"","isMale":"","creationTime":"","ipAddress":"","confirmationCode":"","userStatusId":"","id":null}}
4) But I want to send only firstName and password.I dont want send all fields. how can I send the data to server side.
I want json in this format
{"records":{"firstName":"ram","password":"sham"}}
please give me some suggestions....

You just need to overwrite the getRecordData function of the writer. Like this.
writer:
{
type:'json',
root:'records',
getRecordData: function (record) { return {"firstName" :record.data.firstName,"password": record.data.password}; },
},

nscrob's answer has less coding so it may be preferred, but there is also a built-in config for this on the model: persist: false. It keeps the model field from being sent to the server side.
IMHO the model configs don't seem to get used as well as they should even in the sencha examples (or maybe because they are not used in the sencha examples). I think it also saves a miniscule amount of resources if you define the data types in the model as opposed to letting the client work it out, for example:
Ext.define('ab.model.sn.UserModel',{
extend: 'Ext.data.Model',
//idproperty:'userId',//fields property first position pk.
// using field type definitions and explicit persistance
fields: [
{name: 'userId', type: 'int', persist: false},
{name: 'firstName', type: 'string'},
{name: 'middleName', type: 'string', persist: false},
{name: 'lastName', type: 'string', persist: false},
{name: 'languageId', type: 'int', persist: false},
{name: 'primaryEmail', type: 'string', persist: false},
{name: 'birthDate', type: 'date', dateFormat: 'c', persist: false},
{name: 'password', type: 'string'},
{name: 'securityQuestionId', type: 'int', persist: false},
{name: 'securityQuestionAnswer', type: 'string',persist: false},
{name: 'isMale', type: 'bool', persist: false},
{name: 'creationTime', type: 'date', dateFormat: 'c', persist: false},
{name: 'ipAddress', type: 'string', persist: false},
{name: 'confirmationCode', type: 'string', persist: false},
{name: 'userStatusId', type: 'int', persist: false}
],
proxy:
{
type:'ajax',
//type:'localstorage',
//id:'users',
api:
{
read:'http://localhost/balaee/Balaee/index.php/SocialNetworking/user/AuthenticateLogin',
create:'http://localhost/balaee/Balaee/index.php/SocialNetworking/user/AuthenticateLogin122',
update:'http://localhost/balaee/Balaee/index.php/SocialNetworking/user/AuthenticateLogin123'
},//end of api
reader:
{
type:'json',
},//end of reader
writer:
{
type:'json',
root:'records',
},//End of writer
}//end of proxy
});
Like I said, there is some more coding but I thought I would throw this out there as the built-in handling for this scenario (instead of the override). You could also drop the field type definitions if you wanted, they aren't required to define the persist property.

Related

How to implement Dynamic Grid in Extjs?

I want to implement dynamic grid in Extjs. I have found this How do you create table columns and fields from json? (Dynamic Grid) and the accepted answer looks good.
In my case I have no proxy store but a proxy model:
fields: [ {name: 'id', type: 'int', persist: false},
{name: 'gender', type: 'auto'},
{name: 'name', type: 'auto'},
{name: 'age', type: 'int'}],
identifier: 'sequential', // to generate -1, -2 etc on the client
proxy: {
type: 'rest',
idParam: "id",
url:'http://localhost:3000/posts',
api:
{
read : 'http://localhost:3000/db',
create: 'http://localhost:3000/posts',
update : 'http://localhost:3000/posts' ,
destroy : 'http://localhost:3000/posts'
},
headers: {'Content-Type': "application/json" },
reader: {
type: 'json',
rootProperty:'posts',
totalProperty: 'total'
},
writer: {
type: 'json'
}
My store looks like is:
model: 'ThemeApp.model.peopleModel',
storeId: 'peopleStore',
pageSize: 500,
autoLoad: true,
autoSync: true,
pageSize: 5,
autoLoad: {start: 0, limit: 5},
autoSync: true,
sorters: [{
property : 'age',
direction:'ASC'
}],
groupField: 'gender'
});
In my view I have defined columns:[] But I don't know where to call metachange function.
Can anyone tell me where to use metachange function and should I use metachange function of store or proxy?
Generally you don't want to configure proxy on the model, that is only useful when you want to use standalone Model instances without a store.
Move the proxy config to the Store, and make the server respond to read requests with additional metadata object, which you can then use in the metachange event handler to configure the grid.
Using Reader metadata is the right way to do "dynamic" Grids.

JSON data not loading - ExtJS

I cannot get any of my json data to load into my combobox. Here's my code:
app/data/mydata.json
{
images: [
{name: 'Image one', url:'/GetImage.php?id=1', size:46.5, lastmod: new Date(2007, 10, 29)},
{name: 'Image Two', url:'/GetImage.php?id=2', size:43.2, lastmod: new Date(2007, 10, 30)}
]
}
inside my app.js
var store4 = new Ext.data.JsonStore({
// store configs
storeId: 'myStore',
autoLoad: true,
proxy: {
type: 'ajax',
url: 'app/data/mydata.json',
reader: {
type: 'json',
root: 'images',
idProperty: 'name'
}
},
});...
my combobox inside app.js
{ xtype: 'combobox', queryMode: 'local', padding: 5, store: store4, displayField: 'name', typeAhead: true, emptyText: 'JSON', id: 'test' },
Any ideas?
Cheers!
That isn't valid JSON:
Labels should be wrapped in quotes, eg "name". You should also use double quotes, not single for quoting strings.
You can't use new Date() in JSON, it's not valid. Have a look at Ext.data.Field and the information around the dateFormat parameter. You send the date back as a string and give it a format so Ext can parse it for you.
Also, you're missing field definitions. You need to create an Ext.data.Model subclass with the fields you're going to use in the store.
Ext.define('Image', {
extend: 'Ext.data.Model',
fields: ['name', 'url', 'size']
});
var store = new Ext.data.Store({
model: 'Image',
// ..
});

Cannot load stores using jsonp extjs4.1

I am trying to load ext data stores using jsonp. The below code is working fine when i am using ajax and making requests on the same domain.
The store definition:
var baseUrl = 'http://localhost:8090/';
Ext.define('Ktimatologio.store.NewWholeBlockStore', {
extend: 'Ext.data.Store',
alias: 'widget.newsingleblockstore',
requires: ['Ktimatologio.model.NewWholeBlockModel'],
model: 'Ktimatologio.model.NewWholeBlockModel',
groupField: 'search_tag',
fields: [
{name:'id', mapping:'id'},
{name:'id1', mapping:'id1'},
{name: 'text', mapping: 'text'},
{name: 'title', mapping: 'title'},
{name: 'fek', mapping: 'fek'},
{name: 'date', mapping: 'date'},
{name: 'descr', mapping: 'description'},
{name: 'model', mapping: 'model'},
{name: 'body', mapping: 'body'},
{name: 'type', mapping: 'type'},
{name: 'history', mapping: 'history'},
{name: 'src', mapping: 'url'},
{name: 'search_tag', mapping: 'search_tag'},
{name: 'new_element', mapping: 'new_element'},
{name: 'new_table', mapping: 'new_table'}
],
autoLoad: true,
proxy: {
//type:'ajax',
type:'jsonp',
url: baseUrl + 'openbd/ktimatologio-final/resources/cfScripts/nea_stoixeia/GetNewTables.cfc?',
extraParams: {
method: 'getNewTables'
},
reader:{
type: 'json',
root: 'data'
}
}
When i run the code i see an error on firebug:
SyntaxError: invalid label
{"data":[{"id":"1_n_2308_1995","id1":1,"title":"Άρθρο 1&nbspΦΕΚ Α΄ 114&nbsp15.6....
GetNew...llback2 (line 1, column 1)
I am stuck!
Any help is much appreciated!
Tom
Greece
JSONP service must actually return a function call not just JSON back. Google for some examples.

Ext.JS Prevent Proxy from sending extra fields

Here is my model:
Ext.define('A.model.Group', {
extend: 'Ext.data.Model',
fields:['id', 'name'],
proxy: {
type: 'rest',
url: '/group',
reader: {
type: 'json',
root: 'data'
},
writer: {
type: 'json',
writeAllFields: false
}
}
});
The model is being used in a Tree via a TreeStore
The problem is that when a PUT, POST or DELETE method is done, instead of sending only fields from the model in the JSON payload, fields from Ext.data.NodeInterface are also sent. Here is an example payload:
{"id":"","name":"TestGroup","parentId":"8","index":0,"depth":3,"checked":null}
I don't want the extra fields parentId, index, depth, and checked to be sent. What is the best way to do this? I don't want to have to ignore them on the server.
If you wan't to send only specific data to server, writeAllFields is not the solution as if is set to false it only sends the modified fields.
The solution for your problem is defining your own writer and overriding the method getRecordData here is a posible example:
var newWriter = Ext.create('Ext.data.writer.Json',{
getRecordData: function(record){
return {'id':record.data.id,'name':record.data.name};
}
})
Ext.define('A.model.Group', {
extend: 'Ext.data.Model',
fields:['id', 'name'],
proxy: {
type: 'rest',
url: '/group',
reader: {
type: 'json',
root: 'data'
},
writer: newWriter
}
});
the NodeInterface adds these fields into your model:
{name: 'parentId', type: idType, defaultValue: null},
{name: 'index', type: 'int', defaultValue: null, persist: false},
{name: 'depth', type: 'int', defaultValue: 0, persist: false},
{name: 'expanded', type: 'bool', defaultValue: false, persist: false},
{name: 'expandable', type: 'bool', defaultValue: true, persist: false},
{name: 'checked', type: 'auto', defaultValue: null, persist: false},
{name: 'leaf', type: 'bool', defaultValue: false},
{name: 'cls', type: 'string', defaultValue: null, persist: false},
{name: 'iconCls', type: 'string', defaultValue: null, persist: false},
{name: 'icon', type: 'string', defaultValue: null, persist: false},
{name: 'root', type: 'boolean', defaultValue: false, persist: false},
{name: 'isLast', type: 'boolean', defaultValue: false, persist: false},
{name: 'isFirst', type: 'boolean', defaultValue: false, persist: false},
{name: 'allowDrop', type: 'boolean', defaultValue: true, persist: false},
{name: 'allowDrag', type: 'boolean', defaultValue: true, persist: false},
{name: 'loaded', type: 'boolean', defaultValue: false, persist: false},
{name: 'loading', type: 'boolean', defaultValue: false, persist: false},
{name: 'href', type: 'string', defaultValue: null, persist: false},
{name: 'hrefTarget', type: 'string', defaultValue: null, persist: false},
{name: 'qtip', type: 'string', defaultValue: null, persist: false},
{name: 'qtitle', type: 'string', defaultValue: null, persist: false},
{name: 'children', type: 'auto', defaultValue: null, persist: false}
two of them dont have `persist' property.
Most of NodeInterface's fields default to persist: false. This means they are non-persistent fields by default. Non-persistent fields will not be saved via the Proxy when calling the TreeStore's sync method or calling save() on the Model. In most cases, the majority of these fields can be left at their default persistence setting, but there are cases where it is necessary to override the persistence of some fields. The following example demonstrates how to override the persistence of a NodeInterface field. When overriding a NodeInterface field it is important to only change the persist property. name, type, and defaultValue should never be changed.
Override the fields like this:
{ name: 'iconCls', type: 'string', defaultValue: null, persist: true },
You can add a serializer to the fields in the model you do not want to send to the server.
var makeUndefined = function(value, record) {
return undefined;
}
var fieldsOfYourModel = [
{
serialize: makeUndefined,
name: 'parentId'
},
{
serialize: makeUndefined,
name: 'index'
}
];
serialize is a function which converts the Model's value for this Field into a form which can be used by whatever Writer is being used to sync data with the server. http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.data.Field-cfg-serialize
serialize is available since Ext JS 4.1.1.

Sencha Touch - access 1 to 1 model relationship

I'm trying to access the following JSON from my model store. I have no problem accessing the root (Name and Address) but i can't access anything in Financials (NetWorth or Income). I've verified the JSON below is being returned from the server.
I know this has to be super easy but every example I've seen is showing how to access a 1 to many relationship. My model is a 1 to 1. Person->Financials. Right now I don't have any associations setup as I don't know how to setup a 1 to 1 relationship. I've tried associations, I've tried belongsTo, I've tried Financials.NetWorth from inside my itemTPL. Nothing.
Can someone please show me the light?
JSON returned from server
[{
"PersonName": "John Smith",
"Address": "123 main street",
"Financials":
[{
"NetWorth": "$500,000",
"Income":"$67,000"
}]
}]
I registered my Models.
Ext.regModel('Person', {
fields: [
{name: 'Name', type:'string'},
{name: 'Address', type: 'string'},
],
});
Ext.regModel('Financials',{
fields: [
{name: 'NetWorth', type:'string'},
{name: 'Income', type: 'string'},
],
});
And registered the store
var commStore = new Ext.data.Store({
model: 'Person',
proxy: {
type: 'ajax',
url : 'Business/GetData',
reader: {
type: 'json',
}
},
autoLoad:false,
});
and displaying back in a list
var commList = new Ext.List({
fullscreen: false,
itemTpl : '<div>{PersonName}</div><div>{Business.NetWorth}</div>',
store: commStore,
height:500,
width:"100%",
});
Any help would be much appreciated.
Beginner myself too, but it seems follwing could help (not tested with your code)
Have only on model:
Ext.regModel('Person', {
fields: [
{name: 'Name', type:'string'},
{name: 'Address', type: 'string'},
{name: 'NetWorth', type:'string', mapping 'Financials.NetWorth'},
{name: 'Income', type: 'string', mapping 'Financials.Income'},
],
});
and in template code refer with the names
itemTpl : '<div>{PersonName}</div><div>{Business.NetWorth}</div>',
becomes
itemTpl : '<div>{PersonName}</div><div>{NetWorth}</div>',
You say that your relationship is 1-to-1, but your JSON data returns an array(with 1 item, but nonetheless an array, because you use "[]" brackets) for Financials.
This means that Person should become something like this:
Ext.regModel('Person', {
fields: [
{name: 'Name', type:'string'},
{name: 'Address', type: 'string'},
],
hasMany: [
{name: 'person', model: 'Person'}
]
});