Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extjs4 How to change a Model dynamically? [closed]

Tags:

model

extjs

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?

like image 988
Pierluigi B Web Developer Avatar asked Jun 07 '12 11:06

Pierluigi B Web Developer


1 Answers

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();

        });

    }
});
like image 169
egerardus Avatar answered Oct 27 '22 04:10

egerardus