How can a model in Extjs only read one field from a call to a service that returns a json with multiple nodes? - extjs

I would like to ask you a question with the use of a model that calls a data reading service which returns a json.
All fields are declared in the model.
When the model is used in the creation of a store, it consequently calls a data reading service which is returned in json format. When the delete service is launched, which expects to receive only the ID field, it goes into error because the store from the sync method passes all the fields.
How can I make sure that only the ID field is passed to the service when calling the sync mode?
I also tested it by creating a model with only one field:
fields: ['firstName', {
type: 'int',
name: 'ID'
}],
Even if only one field is specified in the model, the store is initialized with all the fields coming from the json and then it correctly executes the remove method but when the sync is launched it goes into error because all the fields are present and not just the ID.
This is the model:
Ext.define('AmpelideWeb.model.VignaToponimo', {
extend: 'AmpelideWeb.model.Base',
fields: [{
name: 'ID',
type: 'int'
},
{
name: 'CODICE',
type: 'string'
},{
name: 'DESCRIZIONE',
type: 'string'
},{
name: 'SIAN_CODICE',
type: 'string'
},{
name: 'SIAN_EXPFLG',
type: 'string'
},
{
name: 'ID_REGIONE',
type: 'int'
},{
name: 'ID_PROVINCIA',
type: 'int'
}],
statics: {
baseUrl: 'vigne/toponimi'
},
});
This is the model Base:
Ext.define('AmpelideWeb.model.Base', {
extend: 'Ext.data.Model',
identifier: 'negative',
idProperty: 'ID',
inheritableStatics: {
format: 'json',
idParam: 'ID',
readMethod: 'POST',
costantUrl:'http://192.168.24.8:8080/API/v1/'
},
schema: {
proxy: {
type: 'ajax',
idParam: '{idParam}',
paramsAsJson: false,
api: {
create : '{costantUrl}'+'{baseUrl}'+'/insert',
read : '{costantUrl}'+'{baseUrl}',
update : '{costantUrl}'+'{baseUrl}'+'/edit',
destroy : '{costantUrl}'+'{baseUrl}'+'/delete'
},
actionMethods: {
create: 'POST',
read: '{readMethod}',
update: 'POST',
destroy: 'POST'
},
reader: {
type: '{format}'
},
writer: {
//rootProperty:'',
type: '{format}',
writeAllFields: true,
allowSingle: false,
},
}
}
});
This is delete method:
onDeleteClick: function () {
var form = Ext.getCmp('DettaglioVignaToponimo');
let vignaToponimoIdDelete = this.vignaToponimoId;
let store = Ext.create('Ext.data.Store', {
model: 'AmpelideWeb.model.VignaToponimoDelete',
});
store.load();
store.proxy.paramsAsJson = true;
if (form.getValues().ID!==null){
Ext.Msg.confirm('Eliminazione Vigne Toponimi', 'Se sicuro di voler eliminare il dato selezionato ?', function (id, value) {
if (id === 'yes') {
store.proxy.headers = {'Content-Type': 'application/x-www-form-urlencoded'};
const record = new AmpelideWeb.model.VignaToponimoDelete({ID: vignaToponimoIdDelete});
store.remove(record);
store.sync({
success: function (batch) {
Ext.Msg.alert('Eliminazione dati Vigne Toponimi!', 'Eliminazione Vigne Toponimi avvenuta correttamente', function (btn) {
});
},
failure: function (batch, opt) {
responseObj = batch.exceptions[0].error.response.responseJson;
Ext.Msg.alert('Eliminazione Vigne Toponimi fallita', 'messaggio di errore: ' + responseObj.message);
}
});
}else{
return false;
}
})
}else{
Ext.Msg.alert('Eliminazione Vigne Toponimi fallito', 'messaggio di errore: ID Vigne Toponimi è null, nessun dato da eliminare.');
}
},

Even if only one field is specified in the model, the store is initialized with all the fields coming from the json and then it correctly executes the remove method but when the sync is launched it goes into error because all the fields are present and not just the ID.
Two things:
Ext dynamically adds fields into models based on data. It encourages to not maintain field metadata and make it more flexible.
writeAllFields is true, that's why proxy sending all parameters.
writeAllFields make sense only for UPDATE operation, but anyways we don't have a control on request type here.
As I understand, you want to process the data before sending request. I think transform of Ext.data.writer.Writer will be good approach.
You can have in writer it like below:
writer: {
type: 'json',
transform: function(data, request) {
var requestAction = request.getAction(),
serialized;
// keep only id if a delete operation
serialized = (requestAction == "delete") ? { id: data.id } : data;
return serialized;
}
}
Fiddle Link

Related

saving data to session storage with Ext.data.ArrayStore

Could anyone give an example of storing array of model/objects recieved and parsed from Ajax Request in Ext.data.ArrayStore (session storage)?
At the moment I am only able to store it separately in session storage.
userModelProxyKey "0"
userModelProxyKey-0
"{"login":"username","locked":false,"internalUser":false,"name":"","email":"","sid":""}"
My model
Ext.Loader.setPath('Model','./js/model');
Ext.require('Model.User');
Ext.define('Store.UserStore', {
extend: 'Ext.data.ArrayStore',
model: 'Model.User',
storeId: 'userStore',
proxy: {
type: 'sessionstorage',
id: 'userStoreProxyKey'
}
});
My store
Ext.Loader.setPath('Model','./js/model');
Ext.require('Model.User');
Ext.define('Store.UserStore', {
extend: 'Ext.data.ArrayStore',
model: 'Model.User',
storeId: 'userStore',
proxy: {
type: 'sessionstorage',
id : 'userStoreProxyKey'
}
});
Saving to model to session storage:
var user = Ext.create('Model.User', {'id':0,'login': jsonData.login});
user.save();
Attempting to save to storage
var userStore = Ext.create('Store.UserStore');
var userArray = new Array(user);
userStore.add(userArray);
userStore.sync();
and if I try to print number of records I get 0
console.log("User Count: " + userStore.count());

Problems met when using extjs association model with mongoose nested shcema, sub data missing in post

I am using ExtJS+mongoDB to implement an app. I use node.js as the server and express module to create REST api.
In details, I use: ExtJS 4.1.3 + mongoose 1.2.17 + express 1.2.17 + mongodb 2.4, running on Node.js v0.10.3.
The codes ExtJS part(orgnised in MVC):
The Model part contains two models, PvdcPrice and PvdcPriceDetails, they have "hasMany" relationship.
PvdcPrice.js:
Ext.define('App.model.PvdcPrice', {
extend : 'Ext.data.Model',
fields : [{
name : '_id',
type : 'Number'
}, {
name : 'Type',
type : 'string'
}, {
name : 'MaxDiscount',
type : 'Number'
}],
hasMany : [{
name : 'prices',
model : 'App.model.PvdcPriceDetail',
associationKey : 'prices'
}],
proxy : {
type : 'rest',
url : '/pvdcprices',
reader : {
type : 'json',
root : 'data',
successProperty : 'success'
}
}
});
PvdcPriceDetail.js:
Ext.define('App.model.PvdcPriceDetail', {
extend : 'Ext.data.Model',
fields : [{
name : 'ID',
type : 'Number'
}, {
name : 'Location',
type : 'string'
}, {
name : 'Edition',
type : 'string'
}, {
name : 'MonthlyPrice',
type : 'Number'
}, {
name : 'OneTimePrice',
type : 'Number'
}
]
});
The Controller part, as it is too long I put only the store creating part here:
var pvdcPrice = Ext.create('Ext.data.Store', {
model : "App.model.PvdcPrice",
data : [{
"_id" : 1,
"Type" : "pvdc",
"MaxDiscount" : "0"
}]
});
var priceInfo = pvdcPrice.first();
var pvdcPriceDetails = priceInfo.prices();
pvdcPriceDetails.add({
'ID' : 1,
'Location' : 'SNJ',
'Edition' : 'Basic',
'MonthlyPrice' : 906,
'OneTimePrice' : 777
});
pvdcPriceDetails.add({
'ID' : 2,
'Location' : 'ATL',
'Edition' : 'Standard',
'MonthlyPrice' : 906,
'OneTimePrice' : 777
});
pvdcPriceDetails.add({
'ID' : 3,
'Location' : 'ATL',
'Edition' : 'Standard',
'MonthlyPrice' : 906,
'OneTimePrice' : 777
});
pvdcPrice.sync();
var record = pvdcPrice.first();
console.log(record.get('Type'));
record.prices().each(function(r) {
console.log(r.get('Location'));
console.log(r.get('Edition'));
});
The Node.js part, the server script is app.js:
var express = require('express'),
app = module.exports = express();
// MongoDB
var mongoose = require('mongoose'),
db = mongoose.connect('mongodb://127.0.0.1/IaaSDB'),
//create sub schema of pvdc price schema
PriceDetailSchema = new mongoose.Schema({
ID: Number,
Location: String,
Edition: String,
MonthlyPrice: Number,
OneTimePrice: Number
}),
//create the Pvdc price info Model using the 'pvdcPrice' collection as a data-source
PvdcPrice = mongoose.model('pvdcPrice', new mongoose.Schema({
Type: String,
MaxDiscount: String,
prices: [PriceDetailSchema]
}));
// Configuration
app.configure(function () {
//app.set('views', __dirname + '/views');
//app.set('view engine', 'jade');
app.use(express.bodyParser());//parse JSON into objects
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/IaaSPriceTool'));
});
app.configure('development', function () {
app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
});
app.configure('production', function () {
app.use(express.errorHandler());
});
// Routes
app.get('/', function (req, res) {
res.redirect('/index.html');
});
/*
Pvdc Price Information CRUD web service
*/
app.get('/pvdcprices', function (req, res) {
PvdcPrice.find({}, function (err, pvdcprices) {
res.contentType('json');
res.json({
success: true,
data: pvdcprices
});
});
});
app.get('/pvdcprices/:id', function(req, res){
PvdcPrice.find({_id: req.params.id}, function (err, pvdcPrices) {
res.contentType('json');
res.json({
success: true,
data: pvdcPrices
});
});
});
app.post('/pvdcprices', function (req, res) {
console.log("[200] " + req.method + " to " + req.url);
console.log(req.body);
var newPriceInfo = new PvdcPrice();
var newPriceInfoData = req.body;
//remove the id which the client sends since it is a new pvdc price
delete newPriceInfo['_id'];
newPriceInfo.set(newPriceInfoData);
newPriceInfo.save(function (err, pvdcPrice) {
res.contentType('json');
res.json({
success: !err,
data: pvdcPrice
});
});
});
app.listen(3000);
console.log("Express server listening on port %d in %s mode", 3000, app.settings.env);
After then, I use firebug to debug the frontend, I can see from the browser console that the contend of pvdc price is shown:
POST http://localhost:3000/pvdcprices?_dc=1369740182183 200 OK 27ms
pvdc
Basic
ATL
Standard
ATL
Standard
This means that the association model in ExtJS works and I can see the content of pvdcPrice.
The json structure in ExtJS should be:
{
"data" :{
"_id" : 1,
"Type" : "pvdc",
"MaxDiscount" : "0",
"prices" : [{
'ID' : 1,
'Location' : 'SNJ',
'Edition' : 'Basic',
'MonthlyPrice' : 906,
'OneTimePrice' : 777
},{
'ID' : 2,
'Location' : 'ATL',
'Edition' : 'Standard',
'MonthlyPrice' : 906,
'OneTimePrice' : 777
},{
'ID' : 3,
'Location' : 'ATL',
'Edition' : 'Standard',
'MonthlyPrice' : 906,
'OneTimePrice' : 777
}]
}
}
But the reponse from node.js is success: false.
Then in the console of node.js part, I print the request body of post in node.js, it is:
[200] POST to /pvdcprices?_dc=1369734975208
{ _id: 1, Type: 'pvdc', MaxDiscount: 0, id: null }
The sub content of "prices" is missing, only the main part of pvdcPrice is posted to server.
Could someone point out what causes the missing during the post process?
Really appreciate the helps :)
Solved this problem finally, the key is that Ext.data.writer.Json in ExtJS 4 does not support association well.
http://www.sencha.com/forum/showthread.php?141957-Saving-objects-that-are-linked-hasMany-relation-with-a-single-Store
This link offered some solutions.
I use Extjs 4.1.1 a, and add the DeepJson into the Extjs 4.1 source folder:
/**
* #class Ext.data.writer.DeepJson This class is used to write
* {#link Ext.data.Model} data to the server in a JSON format.
*
* It overrides the original Ext.data.writer.Json since the Json can not handle
* hasMany association, it can only transform the outside part into Json, the
* inside data will be omiited.
*
* #Yi Fang Reference:
* http://www.sencha.com/forum/showthread.php?141957-Saving-objects-that-are-linked-hasMany-relation-with-a-single-Store/page3 23 Mar 2012 6:00 AM
* http://www.sencha.com/forum/showthread.php?141957-Saving-objects-that-are-linked-hasMany-relation-with-a-single-Store/page5 13 Feb 2013 2:57 PM
*
*/
Ext.define('Ext.data.writer.DeepJson', {
extend : 'Ext.data.writer.Json',
getRecordData : function(record, operation) {
// Setup variables
var me = this, i, association, childStore, data;
data = me.callParent(arguments);
// Iterate over all the hasMany associations
for (i = 0; i < record.associations.length; i++) {
association = record.associations.get(i);
if (association.type == 'hasMany') {
data[association.name] = null;
childStore = record[association.storeName];
// Iterate over all the children in the current
// association
childStore.each(function(childRecord) {
if (!data[association.name]) {
data[association.name] = [];
}
// Recursively get the record data for
// children (depth first)
var childData = this.getRecordData.call(
this, childRecord);
/*
* If the child was marked dirty or phantom
* it must be added. If there was data
* returned that was neither dirty or
* phantom, this means that the depth first
* recursion has detected that it has a
* child which is either dirty or phantom.
* For this child to be put into the
* prepared data, it's parents must be in
* place whether they were modified or not.
*/
if (childRecord.dirty
|| childRecord.phantom
|| (childData != null)) {
data[association.name].push(childData);
record.setDirty();
}
}, me);
/*
* Iterate over all the removed records and add them to
* the preparedData. Set a flag on them to show that
* they are to be deleted
*/
Ext.each(childStore.removed, function(
removedChildRecord) {
// Set a flag here to identify removed
// records
removedChildRecord.set('forDeletion', true);
var removedChildData = this.getRecordData
.call(this, removedChildRecord);
data[association.name]
.push(removedChildData);
record.setDirty();
}, me);
}
}
// Only return data if it was dirty, new or marked for deletion.
if (record.dirty || record.phantom || record.get('forDeletion')) {
return data;
}
return null;
}
});
In the PvdcPrice model, update the proxy as
proxy : {
type : 'rest',
url : '/pvdcprices',
reader : {
type : 'json',
root : 'data',
successProperty : 'success'
},
writer : Ext.create('Ext.data.writer.DeepJson')
}
Then the post for nested data works.
belongsTo: 'App.model.PvdcPrice' is missing in 'App.model.PvdcPriceDetail' model class. Its an association problem in your code and you need to map the parent class key with child model. please refer below link (in association session).
http://docs.sencha.com/extjs/4.2.0/#!/guide/data
I hope after making your belongsTo config to 'App.model.PvdcPriceDetail' class it will work fine as expected.
Thanks

Sencha : how to pass parameter to php using Ext.data.HttpProxy?

I have successfully completed this great tutorial : http://www.sencha.com/learn/ext-js-grids-with-php-and-sql/
I just can't use the baseParams field specified with the proxy... Here is my code that follows tutorial description :
__ My Store : Communes.js ____
Ext.define('app.store.Communes', {
extend: 'Ext.data.Store',
id: 'communesstore',
requires: ['app.model.Commune'],
config: {
model: 'app.model.Commune',
departement:'var',
// the proxy with POST method
proxy: new Ext.data.HttpProxy({
url: 'app/php/communes.php', // File to connect to
method: 'POST'
}),
// the parameter passed to the proxy
baseParams:{
departement: "VAR"
},
// the JSON parser
reader: new Ext.data.JsonReader({
// we tell the datastore where to get his data from
rootProperty: 'results'
},
[
{
name: 'IdCommune',
type: 'integer'
},
{
name: 'NomCommune',
type: 'string'
}
]),
autoLoad: true,
sortInfo:{
field: 'IdCommune', direction: "ASC"
}
}
});
_____ The php file : communes.php _____
<?php
/**
* CREATE THE CONNECTION
*/
mysql_connect("localhost", "root", "pwd") or
die("Could not connect: " . mysql_error());
mysql_select_db("databasename");
/**
* INITIATE THE POST
*/
$departement = 'null';
if ( isset($_POST['departement'])){
$departement = $_POST['departement']; // Get this from Ext
}
getListCommunes($departement);
/**
*
*/
function getListCommunes($departement) {
[CODE HERE WORK FINE : just a connection and query but $departement is NULL]
}
?>
There is no parameter passed as POST method... Any idea?
That´s because the baseParams are part of the querystring, they are not passed in the POST body but in the url instead.
I don´t know PHP but probably this works:
if ( isset($_GET['departement'])){
$departement = $_GET['departement']; // Get this from Ext
}

ExtJS 4: Ext.grid.Panel Ext.PagingToolbar buttons (first, previous, next, last) not passing start and limit parameters

I'm having difficulty getting the paging toolbar to work. The initial load passes the "start" and "limit" parameter to the server proxy and the data loads fine in the grid. However, when clicking the "Next" button in the paging toolbar, the "start" and "limit" parameters don't get passed properly and the web method bombs out because it expects those parameters. If you can help me fix the root problem, that would be awesome. But if not, and you're able to help me override the buttons, that's also fine, so I can put in a temporary fix until I figure out what's wrong.
Exception:
POST http://{domain}/Controls/ObjectList/ObjectListService.asmx/GetObjectList?_dc=1348591244365 500 (Internal Server Error) ext-all-debug.js:36837
Ext.define.request ext-all-debug.js:36837
Ext.define.doRequest ext-all-debug.js:49508
Ext.define.read ext-all-debug.js:39082
Ext.define.load ext-all-debug.js:47668
Base.implement.callParent ext-all-debug.js:3728
Ext.define.load ext-all-debug.js:50160
Ext.define.read ext-all-debug.js:47399
Ext.define.loadPage ext-all-debug.js:50404
Ext.define.nextPage ext-all-debug.js:50409
Ext.define.moveNext ext-all-debug.js:102105
Ext.define.fireHandler ext-all-debug.js:79530
Ext.define.onClick ext-all-debug.js:79520
(anonymous function)
Ext.apply.createListenerWrap.wrap ext-all-debug.js:9171
{"Message":"Invalid web service call, missing value for parameter: \u0027query\u0027.","StackTrace":" at System.Web.Script.Services.WebServiceMethodData.CallMethod(Object target, IDictionary`2 parameters)\r\n at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary`2 parameters)\r\n at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}
===========================
Source Code:
var itemsPerPage = 30;
var store = new Ext.data.Store({
proxy: new Ext.ux.AspWebAjaxProxy({
url: '/Controls/ObjectList/ObjectListService.asmx/GetObjectList',
actionMethods: {
create: 'POST',
destroy: 'DELETE',
read: 'POST',
update: 'POST'
},
reader: {
type: 'json',
model: 'Object',
totalProperty: 'd.recordCount',
//idProperty: 'object_id',
root: 'd.resultSet'
},
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
}),
pageSize: itemsPerPage,
noCache: false,
//autoLoad: true
autoLoad: {
params: {
//query: '',
start: 0,
limit: itemsPerPage
}
}
});
...
Ext.define('ObjectGrid', {
extend: 'Ext.grid.Panel',
initComponent: function () {
var me = this;
Ext.applyIf(me, {
store: store,
forceFit: true,
autoScroll: true,
height: 750,
loadMask: true,
columns: [
],
...
bbar: Ext.create('Ext.PagingToolbar', {
store: store,
displayInfo: true,
pageSize: 30,
displayMsg: 'Displaying records {0} - {1} of {2}',
emptyMsg: 'No records to display'
// type: 'pagingmemory',
// listeners: {
// afterrender: {
// single: true,
// fn: function (thispaging) {
// thispaging.first.on('click', function () {
// Ext.Msg.alert('first', 'first');
// });
// thispaging.prev.on('click', function () {
// Ext.Msg.alert('prev', 'prev');
// });
// thispaging.next.on('click', function () {
// Ext.Msg.alert('next', 'next');
// });
// thispaging.last.on('click', function () {
// Ext.Msg.alert('last', 'last');
// });
// }
// }
// }
// listeners: {
// 'click' : function(which) {
// alert('you have clicked');
// }
// }
}) // bbar
});
me.callParent(arguments);
}
});
update #1:
The parameters are being lost between these two calls in the stack trace mentioned above.
line 39082:
this.requests.5.options.params = "{}"
(5) being the current object
line 47668:
operation.start = 2
operation.limit = 30
update #2:
Ext.define('Ext.ux.AspWebAjaxProxy', {
extend: 'Ext.data.proxy.Ajax',
require: 'Ext.data',
//processData: false,
buildRequest: function (operation) {
var params = Ext.applyIf(operation.params || {}, this.extraParams || {}),
request;
params = Ext.applyIf(params, this.getParams(params, operation));
if (operation.id && !params.id) {
params.id = operation.id;
}
params = Ext.JSON.encode(params);
request = Ext.create('Ext.data.Request', {
params: params,
action: operation.action,
records: operation.records,
operation: operation,
url: operation.url
});
request.url = this.buildUrl(request);
operation.request = request;
return request;
}
});
Well I guess the trick lies within
// Clone params right now so that they can be mutated at any point further down the call stack
var me = this,
params = operation.params = Ext.apply({}, operation.params, me.extraParams),
request;
I think you can use this to replace your first lines, I guess it should work then.
Please look also at
// Set up the entity id parameter according to the configured name.
// This defaults to "id". But TreeStore has a "nodeParam" configuration which
// specifies the id parameter name of the node being loaded.
if (operation.id !== undefined && params[me.idParam] === undefined) {
params[me.idParam] = operation.id;
}
dunno if you need to update this too.
I tried going back to ExtJS version 4.0.0, but other features in my application are breaking. So I'm sticking with version 4.1.0 and implemented a hack for this proxy so it'll work, so I can have some piece of mind (or is it "peace of mind?").
Ext.define('Ext.ux.AspWebAjaxProxy', {
extend: 'Ext.data.proxy.Ajax',
require: 'Ext.data',
buildRequest: function (operation) {
var params = Ext.applyIf(operation.params || {}, this.extraParams || {}),
request;
params = Ext.applyIf(params, this.getParams(params, operation));
if (params.page == null) {
params.page = operation.page;
params.start = operation.start;
params.limit = operation.limit;
}
if (operation.id && !params.id) {
params.id = operation.id;
}
params = Ext.JSON.encode(params);
request = Ext.create('Ext.data.Request', {
params: params,
action: operation.action,
records: operation.records,
operation: operation,
url: operation.url
});
request.url = this.buildUrl(request);
operation.request = request;
return request;
}
});
//});

ExtJS: store - proxy - writer: how to always add/set a value to records when sync?

After two days of struggling, I've made my own Ext.data.Store class that works (see code below).
Note that, even though all the configuration of the proxy and its writer are taken in account, the configuration writeAllFields: true is ignored and only the changed values are sent (which is a big problem to me).
So, now, to circumvent that (huge) problem, I'd like to always add a pre-defined value to the records that are sent (it's always one value, something like id_partner: 3). I need this for security reasons.
Ext.define('Ext.data.StoreHandleErrors', {
extend: 'Ext.data.Store',
alias: 'data.storehandleerrors',
constructor: function(config) {
config.autoLoad= true;
config.autoSync= true;
config.proxy.type= 'ajax';
config.proxy.reader= {
type: 'json',
successProperty: 'success',
root: 'data',
messageProperty: 'message'
};
config.proxy.writer= {
type: 'json',
writeAllFields: true,
root: 'data'
};
config.proxy.listeners= {
exception: function(proxy, response, operation) {
/* Code to handle exception */
}
};
this.callParent([config]);
this.on(
'write',
function(store, operation) {
/* Code to show how the write op. went */
},
this
);
this.on(
'beforesync',
function(objects_to_sync, opts) {
/* Code to add a pre-defined value to be sent: "id_partner: 3" */
},
this
);
}
});
Any idea how I could do this?
Here's my code that works. It's a hack but it works with both ExtJS 4.0.7 and ExtJS 4.1 beta.
Ext.define('Ext.data.StoreHandleErrors', {
extend: 'Ext.data.Store',
alias: 'data.storehandleerrors',
constructor: function(config) {
/* (!!) proxy properties overwrite */
config.autoLoad= true;
config.autoSync= true;
config.proxy.type= 'ajax';
config.proxy.reader= {
type: 'json',
successProperty: 'success',
root: 'data',
messageProperty: 'message'
};
config.proxy.writer= {
type: 'json',
writeAllFields: true,
root: 'data'
};
config.proxy.listeners= {
exception: function(proxy, response, operation) {
/* generic exception handling here */
}
};
this.callParent([config]);
this.on(
'add',
function(store, records, index, eOpts) {
/* 27/04/2012 (!!) Hack: force property on all records */
for (var i = 0; i <records.length; i++) {
records[i].data.id_partenaire=this.idPartenaire;
};
},
this
);
this.on(
'beforesync',
/* 27/04/2012 (!!) Hack: force property on all records to false
* and then ExtJs sees it's not the same so update
* the value accordingly
*/
function(sync, opts) {
if (typeof sync.create!='undefined') {
for (var i = 0; i <sync.create.length; i++) {
sync.create[i].modified.id_partenaire=false;
};
}
if (typeof sync.update!='undefined') {
for (var i = 0; i <sync.update.length; i++) {
sync.update[i].modified.id_partenaire=false;
};
}
},
this
);
/* (!!) remember the property (it's not copied
* when calling this.callParent([config]); )
*/
this.idPartenaire=config.idPartenaire;
}
});
I've found in ExtJs "5.1" that the field will not be sent to the server, even though you've set "writeAllFields" to true, when the field type is not specified in the model..
for instance with this code:
"fields:[
{name:'commission_id', type:'int'},
{name:'name'},
{name:'surname', type:'auto'},
]"
commission_id will be sent even though not changed. Name and Surname Won't be sent if not changed.

Resources