i have a students json data store of a school. The students are enrolled in courses.
And i need, show students by course. So i have the next paginated store:
Ext.define('AM.store.Alumnos', {
extend: 'Ext.data.Store',
model: 'AM.model.Alumno',
autoLoad: false,
start: 0,
pageSize: 20,
remoteSort: true,
proxy: {
type: 'ajax',
url: 'mvc/stores/Alumnos.php',
reader: {
type: 'json',
root: 'data',
successProperty: 'success',
totalProperty: 'total'
}
}
});
And i like, not have a store for each course. Then, when i load the store, send by param the idCourse:
/**
* Muestra la ventana de gestion de un grado.
* #param {int} id course.
* #return {void}
*/
mostrarAbmAlumnos: function(idGradoSolicitado) {
var store = Ext.create('AM.store.Alumnos', {}).load({
params: {idGrado: idGradoSolicitado}
});
}
For the first page, the store works fine, but when i click "next page", the idCourse not trip to server.
Any ideas ?.
I found the solution. When i create the data store, before load it, bind the extraParams at the Proxy.
According the doc:
extraParams : Object Extra parameters that will be included on every
request. Individual requests with params of the same name will
override these params when they are in conflict.
Note: I use ExtJs 4, in previous version, extraParams are called baseParams.
So, the correct code would:
var store = Ext.create('AM.store.Alumnos', {});
store.getProxy().extraParams.idGrado = idGradoSolicitado;
store.load();
And work fine !.
Related
ExtJS6 model is not forming correct proxy urls for dynamic parameters
Model looks like
Ext.define('Testt.model.User', {
extend: 'Ext.data.Model',
fields: ['id', 'name'],
proxy: {
type: 'ajax',
api : {
read : 'api/user/:id',
create : 'api/user',
update : 'api/user/:id',
destroy : 'api/user/:id'
},
reader : {
type : 'json'
},
writer : {
type : 'json'
}
}
});
Now when called to load a user record like
Testt.model.load(27, { success: function(rec){console.log(rec)}})
It does not replace :id with actual 27
If you use the REST Proxy type (http://docs.sencha.com/extjs/6.0.1-classic/Ext.data.proxy.Rest.html) then the IDs will be automatically appended to your URLs. You don't need the ':id' syntax in the urls.
Check out this fiddle to see it working: https://fiddle.sencha.com/#fiddle/1cri
I am working in extjs4 MVC.I am going to stuck at a point where I am going to set dynamically proxy type to 'localstorage' where I am replacing my proxy type which is 'ajax' which is declared in model class.
When I want to store data at client side for that I am changing my model proxy type from ajax to locastorage.but when I am calling save() method on particular model object that data are going to server side not saved at client side.Plese give me some suggestion
1) Here is my model data class
Ext.define('Am.model.sn.UserModel',{
extend: 'Ext.data.Model',
fields: ['userId','firstName','middleName','lastName','languageId','primaryEmail','birthDate','password','securityQuestionId','securityQuestionAnswer','isMale','creationTime','ipAddress','confirmationCode','userStatusId',],
proxy:
{
type:'ajax',
api:
{
read:'index.php/SocialNetworking/user/AuthenticateLogin',
create:'index.php/SocialNetworking/user/AuthenticateLogin',
},//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
Ext.define('Am.controller.sn.UserController',
{
extend:'Ext.app.Controller',
stores:['sn.UserStore','sn.SecurityquestionStore'],
models:['sn.UserModel','sn.SecurityquestionModel'],
views:['sn.user.Login','sn.user.Registration','sn.user.ForgetMyKey','sn.user.SecurityQuestion','sn.user.KpLogin'],
-----
----
init:function()
{
--------
}
remeberMe:function()
{
console.log("check box selected");
var email=this.getUserName().getValue();
var password=this.getPassword().getValue();
var objCheckBox=Ext.getCmp('checkbox');
if(objCheckBox.getValue()==true)
{
window.localStorage.clear();
//code for stoaring data at local storage
var modelObject = Ext.ModelManager.create(
{
primaryEmail:email,
password: password,
}, 'Balaee.model.sn.UserModel');
proxy=modelObject.getProxy();
//proxy=modelObject.getProxy();
proxy.type='localstorage';
//proxy.set(type,'localstorage');
proxy.id='rememberMe';
//proxy.set(id,'rememberMe');
//modelObject.setProxy(proxy);
//console.log("models proxyyyyyyyyyy="+modelObject.getProxy().type+""+modelObject.getProxy().id);
modelObject.setProxy(proxy);
//
I am also trying this but not work
//Ext.apply(proxy,{type:'localstorage',id:'remember' });
modelObject.save();
// code to hide login window
//var obj=Ext.ComponentQuery.query('#loginId');
//console.log("Object name = "+obj[0].id);
//obj[0].hide();
}//end of if statement
else
{
console.log("check box is not selected");
}//end of else statement
},//End of rememberMe function
});
please give me some suggestion.....
I created a sample code for a better understanding of switching proxxies.
//Defining model
Ext.define('User', {
extend: 'Ext.data.Model',
fields: [{name: 'name', type: 'string'}]
});
//creation of ajax proxy
var ajaxProxy = new Ext.data.proxy.Ajax({
id: 'ajaxp',
reader: 'json'
});
//creation of local storage proxy
var lsProxy = new Ext.data.proxy.LocalStorage({
id: 'localp',
reader: 'json'
});
//Create instance of model
var user = Ext.create('User', {
name : 'Pravin Mane',
proxy: ajaxProxy //sets the ajax proxy
});
//Somewhere in your code
user.setProxy(lsProxy); //sets the localstorage proxy
You can set the proxy using the method setProxy(), defined on the Ext.data.Model.
Im looking for a tutorial or an example for sencha touch 2 MVC STORE which deals with Jsonp link and fetches data from there, ONLY MVC BASE .I need to learn how Store, Model, Controller and View interact with each other in MVC based structure . any suggestion ? between I need to understand how to fetch and work with jsonp links and datas, Thanks
Download sencha touch 2 and find oreilly example. In this example in About panel Tweets page loads data from store (reader type is jsonp). Also you should check another examples like touchtweets, geocongress, navigationview etc.
I think it's the best way for start.
I have found the documentation has a lot of good tutorials on understanding sencha touch's MVC structure, as well as each individual topics like stores and models.
MVC in depth part 1:
http://docs.sencha.com/touch/2-0/#!/video/mvc-part-1
MVC in depth part 2:
http://docs.sencha.com/touch/2-0/#!/video/mvc-part-2
The docs also have a guide section that goes over everything that you need to know too.
http://docs.sencha.com/touch/2-0/#!/guide
A simple example of model,store and view using jsonp
How jsonp looks like.
callback({"Message":"Success","Post":[{"id":"35","UserId":"faisalkhalid690","Content":"lol","Time":"2013-12-03 05:28:15"},{"id":"50","UserId":"faisalkhalid","Content":"asdfasdfasdf","Time":"2013-12-03 05:52:27"},{"id":"51","UserId":"faisalkhalid","Content":"sadfasdfasdf","Time":"2013-12-03 05:52:38"},{"id":"52","UserId":"faisalkhalid","Content":"holloa","Time":"2013-12-03 05:52:50"},{"id":"70","UserId":"faisalkhalid690","Content":"hello","Time":"2013-12-04 23:22:52"}]});
Model for this jsonp.
Ext.define('talkbag.model.Comments', {
extend: 'Ext.data.Model',
config: {
idProperty: 'id',
fields: [
{ name: 'id', type: 'auto' },
{ name: 'UserId', type: 'auto' },
{ name: 'Content', type: 'auto' },
{ name: 'Time', type: 'auto' }
]
}
});
Store:
Ext.define('talkbag.store.Comments', {
extend:'Ext.data.Store',
storeId:'Comments',
config:{
autoLoad: true,
model:'talkbag.model.Comments',
proxy: {
type: 'jsonp',
url : 'http://www.litemake.com/ViewComments.php?Pid='+talkbag.User.PostId,
reader: {
type: 'json',
rootProperty: 'Post'
}
}
}
});
View:
Ext.define('talkbag.view.ViewPost.ViewCommentDetail', {
xtype:'ViewCommentDetail',
extend:'Ext.dataview.List',
config:{
store:'Comments',
itemTpl:'<table><tr><td width="80px"><table align="center"><tr><td align="center"><img src="http://www.litemake.com/getPic.php?userId={UserId}" heigth="30px" width="30px"/></td></tr><tr><td style="font-size:0.6em">{UserId}</td></tr></table></td><td style="padding-left:20px"><table><tr><td style="font-size:0.7em; padding:0px 0px 5px 0px">{Content}</td></tr><tr><td style="font-size:0.5em">{Time}</td></tr></table></td></tr></table>'
}
});
If you need some information about JSONP - Server Side, then have a look to
the Sencha Touch API (JSONP)
There you can find serverside methods to handle your JSONP request for common server side programm languages like PHP, Java or ASP.net.
For PHP it would look like this:
// From your Sencha JSONP Store, you will get a callback parameter which we
// need to put in our $callback var, for later usage.
$callback = $_REQUEST['callback'];
// Create the output object.
// this could also be a database output, but remember to
// convert it into an array
$output = array('a' => 'Apple', 'b' => 'Banana');
// start output
// this section switches between a jsonp callback or usual json output.
if ($callback) {
header('Content-Type: text/javascript');
echo $callback . '(' . json_encode($output) . ');';
} else {
header('Content-Type: application/x-json');
echo json_encode($output);
}
As Faisal Khalid already said, the output will look like...
myCallbackName({
"message":"success",
"total":2,
"data":[
{"prename":"Bob","lastname":"example"},
{"prename":"John","lastname":"Beard"}
]
});
... where you've defined myCallbackName as the callback name in your sencha application (store configuration).
The config is called callbackKey and is set to callback by default.
I'm trying to make ExtJs work with backend running WCF RIA services with JSON endpoint enabled. The backend I have uses GetXXX for read data and CommitChanges for create/update/delete data. It also has not ExtJs standard message format, so I have store class defined like this:
function cloneObject(src, dst) {
for (var key in src)
{
dst[key] = src[key];
}
return dst;
}
Ext.define('MyApp.store.Items', {
extend: 'Ext.data.Store',
model: 'MyApp.model.Tax',
autoLoad: true,
autoSync: true,
proxy: {
type: 'ajax',
api: {
read: '/MyApp/MyAppWeb-Web-MyAppDomain.svc/JSON/GetItems',
update: '/MyApp/MyAppWeb-Web-MyAppDomain.svc/JSON/SubmitChanges',
create: '/MyApp/MyAppWeb-Web-MyAppDomain.svc/JSON/SubmitChanges',
destroy: '/MyApp/MyAppWeb-Web-MyAppDomain.svc/JSON/SubmitChanges'
},
reader: {
type: 'json',
root: 'GetItemsResult.RootResults',
successProperty: null,
totalProperty: 'GetItemsResult.TotalCount'
},
writer: {
type: 'json',
root: 'changeSet',
currentOperation: null,
getRecordData: function(record) {
var changeSet = [];
var entity = {
Id: 0,
Operation: 3,
Entity: {
__type: 'Items:#MyApp.Web'
},
OriginalEntity: {
__type: 'Items:#MyApp.Web'
}
};
cloneObject(record.data, entity.Entity);
cloneObject(record.raw, entity.OriginalEntity);
changeSet.push(entity);
return changeSet;
}
}
}
});
As you can in order to accomodate Microsoft JSON endpoint format I had to override getRecordData and create custom JSON object. I can probably replace cloneObject function with merge function, right? (I'm still kind of new to ExtJs, so may be I'm trying to "invent a bicycle" here.
It works more or less as expected for update, however for create and delete I need to create slightly different message format. Different Operation code and no need to send OriginalEntity. However inside getRecordData I don't have information about what kind of operation is being performed. So question #1
What is the best approach here? Override 'write' method as well or is there another way?
Question #2. After any update standard store class would call reader in order to parse response, but response for update is very different then response for GetItems and I have no idea how to handle that.
Any suggestions or links to walk-through on how to tie ExtJs and Domain Services?
I ended up re-writing Proxy class to add support for different parsing for read/write operations. Works pretty well. Let me know if somebody else faces same problems - I will post code samples.
i'm very new to extjs and i'm trying to make some sense of from what i know from Jquery. I want to have an object to be used application wide as key=>val. I think that using a store is the way to go about it but i can't get it to post any parameters. I have tried dozens of variations to call it but no luck. The code i'm using for now is
var store = new Ext.data.JsonStore({
proxy: new Ext.data.HttpProxy({
method: 'POST' ,
url: '/LoadLanguage.html',
}),
autoload: true,
baseParams: {
'code' : code
},
root: '',
fields: [{name: 'Time', mapping: 'Time', type: 'int'}]
});
Problem is that the $_POST variable is always empty and the GET is like http://lordos.home.local/LoadLanguage.html?_dc=1305874986764&page=1&start=0&limit=25
I need it to post the parameters cause GET will not do.
Thanx
I'm trying to understand what you're doing to please forgive me if this is just not going to work for you.
If you want to have a key=>val storage mechenisim I would suggest the KISS method and use a literal JS object to store / get the data.
// Define a namespace.
window.MyNamespace = {};
// Add my config object to hold key => balue
MyNamespace.config = {};
MyNamespace.config = {
key : 'value',
key2 : 'value2'
};
Do do an ajax request I would use...
Ext.Ajax.Request({
method:'POST', // This is the default value, here for you to see.
url:'/LoadLanguage.html',
params: {
'post_key1' : 'post_value1',
'post_key2' : 'post_value2'
},
success:function(response) {
var text = response.responseText;
MyNamespace.config.language = text;
}
});