PDA

View Full Version : How to get a model instance by an Ext.ModelMgr api?



oldrichard
18 Feb 2011, 8:36 PM
I went thought the Extjs4 api and could not find the proper way to get an model instance by Ext.ModelMgr api other than Ext.ModelMgr.create(). There was a sample in the Blog



Ext.regModel('User', {
fields: ['id', 'name', 'age'],
proxy: {
type: 'rest',
url : '/users',
reader: {
type: 'json',
root: 'users'
}
}
});

var UserModel = Ext.getModel('User');
var ed = new UserModel({
name: 'Ed Spencer',
age : 25
});

ed.save({
success: function(ed) {
console.log("Saved Ed! His ID is "+ ed.getId());
}
});


I expected there would be a corresponding like this



var UserModel = Ext.getModel('User');
var newUser = new UserModel({});

newUser.load(123, {
success: function(newUser) {
console.log("Loaded user 123: " + newUser.get('name'));
}
});


I was not able to make this work. Anybody know what's wrong with that?

icflorescu
19 Feb 2011, 6:19 AM
The code you're looking for is this:


var UserModel = Ext.ModelMgr.getModel('User');

UserModel.load(123, {
success: function(newUser) {
console.log("Loaded user 123: " + newUser.get('name'));
}
});


If you have previously registered a User model the above code works fine.

There's a catch, however. Assuming you're testing like everybody with a json file, 123.json must provide an array with a single user, otherwise it won't work.
Which I find a bit strange, there's no point of expecting an array when all you're trying to do is loading a single model instance. But let's be patient, maybe this is one of the things that are going to be revised during the beta stage...

So 123.json must be something like this (note the square brakets):


[
{
"id": 1,
"name": "John Doe",
"email": "[email protected]"
}
]


See more in this (http://www.sencha.com/forum/showthread.php?124163-Model.load-success-callback-params) short thread.

icflorescu
19 Feb 2011, 6:27 AM
There's something else I have noticed and others may benefit from knowing it, you can register your namespaced model like this:


Ext.regModel('App.Data.User', {
fields: [ 'id', 'name', 'email' ]
proxy: {
type: 'rest',
url: 'data/users',
format: 'json'
}
});


And then use it like this:


App.Data.User.load(1, { ... });


The necessary namespace definition is automatically created for you; also note there's no need to declare a model var when you need to use load or create.