I use Extjs4 and MVC. I would like to change my Model's fields dynamically... Something like adding a variable number of fields... Any suggests?
Asked
Active
Viewed 1.5k times
7
-
1possible duplicate of [Dynamic Model with ExtJS 4](http://stackoverflow.com/questions/5751289/dynamic-model-with-extjs-4) – Abdel Raoof Olakara Jun 07 '12 at 11:39
-
What exactly are you trying to do? Can you be a bit more specific? And also what version of ExtJs are you using? – sha Jun 07 '12 at 12:39
-
1Extjs4, for example I have a model with 3 field... I want extend it with other six field... – Pierluigi B Web Developer Jun 07 '12 at 14:34
-
This question should have never been closed as not a real question!! It is a perfectly legitimate question. Don't vote to close just because you don't understand whats being asked. That said, it is duplicate. – Dave Jan 07 '14 at 20:17
1 Answers
12
You can use the model.setFields(fieldsArray)
function, shown here in the API. This method replaces all existing fields on the model with whatever new fields you include in the argument. There is not a static getFields
method to capture the existing fields so as not to overwrite them but it is easy enough to get them using model.prototype.fields
.
I did this recently to attach dynamic permission setting fields to a "User" model before I loaded the user. Here's an example:
Ext.define('myApp.controller.Main', {
extend: 'Ext.app.Controller',
models: [
'User',
],
stores: [
'CurrentUser', // <-- this is not autoLoad: true
'PermissionRef', // <-- this is autoLoad: true
],
views: ['MainPanel'],
init: function() {
var me = this;
// when the PermissionRef store loads
// use the data to update the user model
me.getPermissionRefStore().on('load', function(store, records) {
var userModel = me.getUserModel(),
fields = userModel.prototype.fields.getRange();
// ^^^ this prototype function gets the original fields
// defined in myApp.model.User
// add the new permission fields to the fields array
Ext.each(records, function(permission) {
fields.push({
name: permission.get('name'),
type: 'bool'
});
});
// update the user model with ALL the fields
userModel.setFields(fields);
// NOW load the current user with the permission data
// (defined in a Java session attribute for me)
me.getCurrentUserStore().load();
});
}
});

egerardus
- 11,316
- 12
- 80
- 123
-
I just noticed that this is a duplicate of [this one](http://stackoverflow.com/questions/5751289/dynamic-model-with-extjs-4) after I answered it. I gave the exact same answer there... – egerardus Jun 10 '12 at 16:36