Skip to main content

Rules for Model Associations in ExtJS

Rules for HasMany Associations in ExtJS

  1. Always put your Proxies in your Models, not your Stores, unless you have a very good reason not to *
  2. Always require your child models if using them in hasMany relationships. ** 
  3. Always use foreignKey if you want to load the children at will
  4. Always use associationKey if you return the children in the same response as the parent
  5. You can use both foreignKey and associationKey if you like
  6. Always name your hasMany relationships
  7. Always use fully qualified model names in your hasMany relationship
  8. Consider giving the reader root a meaningful name (other than "data")
  9. The child model does not need a belongsTo relationship for the hasMany to work
Rules for HasOne and BelongsTo Associations in ExtJS:


Put the proxy in the model, unless you have a very good reason not to [1]
 Always use fully qualified model name
 Always set the getterName
 Always set the setterName
 Always set the associationKey, if the foreign object is returned in the same response as this object
 Always set the foreignKey, if you want to load the foreign object at will
 Consider changing the instanceName to something shorter
 The getter behaves differently depending on whether the foreign object is loaded or not. If its loaded, the foreign object is returned. Otherwise, you need to pass in a callback to get it.
 You should set the name property if you plan to override this association.
 You do not need a belongsTo relationship for a hasMany to work
 Set the primaryKey property if the id field of the parent model is not "id"
 Sometimes you need to use uses or requires for the belongsTo association. Watch out for circular references though.
 Calling setter() function does not seem to set the instance. Set object.belongsToInstance = obj  if calling the setter().
HasMany Example :
Ext.define('Assoc.model.Contact', {

    extend:'Ext.data.Model',

    requires:[
        'Assoc.model.PhoneNumber'          /* rule 2 */
    ],

    fields:[
        'name'                             /* id field is inherited from Ext.data.Model */
    ],

    hasMany:[
    {
        foreignKey: 'contact_id',          /* rule 3, 5 */
        associationKey: 'phoneNumbers',    /* rule 4, 5 */
        name: 'phoneNumbers',              /* rule 6 */
        model: 'Assoc.model.PhoneNumber'   /* rule 7 */
}
    ],

    proxy:{                                /* rule 1 */
        type: 'ajax',
        url: 'assoc/data/contacts.json',
        
        reader: {
            type: 'json',
            root: 'contacts'               /* rule 8 */
        }
    }
});

// example usage:

var c = new Assoc.model.Contact({id:99});

/*
 * assuming that PhoneNumber.proxy is AJAX and has a url set to 'phonenumbers', the below function would make an http request like this:
 * /phonenumbers?page=1&start=0&limit=25&filter=[{"property":"contact_id","value":"99"}]
 * ie, it would make a request for all phone numbers, but ask the server to filter them by the contact_id of the Contact, which is 99 in this case
 */
c.phoneNumbers().load(); 

* The store will inherit its model's proxy, and you can always override it
** To make it easy, and avoid potential circular references, you can require them in app.js .

BelongsTo Example:

Ext.define('Assoc.model.PhoneNumber', {
    extend:'Ext.data.Model',

    fields:[
        'number',
        'contact_id'
    ],

    belongsTo:[
    {
      name:'contact',
      instanceName:'contact',
      model:'Assoc.model.Contact',
      getterName:'getContact',
      setterName:'setContact',
      associationKey:'contacts',
      foreignKey:'contact_id'
    }
    ],

    proxy:{
        type:'ajax',
        url:'assoc/data/phone-numbers.json',
        reader:{
            type:'json',
             root:'phoneNumbers'
        }
    }
});

Note about associationKey:
The mapping and associationKey configs do the same thing but do different things and are not going to work together.

I personally would change the server to make it easy on the client to get this data. Or you could extend the reader and handle the raw data when the response comes in to unnest the data.

Eg:
 {name: 'jmeterOverrideEnable', mapping: 'jmeterOptions.overrideOptions.enable', type: 'boolean'},
        {name: 'jmeterOverrideThreads', mapping: 'jmeterOptions.overrideOptions.threads', type: 'number'},
        {name: 'jmeterOverrideRampUpTime', mapping: 'jmeterOptions.overrideOptions.rampUpTime', type: 'number'},
        {name: 'jmeterOverrideIterations', mapping: 'jmeterOptions.overrideOptions.iterations', type: 'number'},
        {name: 'jmeterOverrideDuration', mapping: 'jmeterOptions.overrideOptions.duration', type: 'number'},
        {name: 'jmeterOverrideEnginesVsUsers', mapping: 'jmeterOptions.overrideOptions.engines_vs_users', type: 'number'}

Comments

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here.
    Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Online Training from India . or learn thru JavaScript Online Training from India. Nowadays JavaScript has tons of job opportunities on various vertical industry.
    ES6 Training in Chennai

    ReplyDelete

Post a Comment

Popular posts from this blog

ExtJS - Grid panel features

What can we do with ExtJS GridPanel? I have to develop a lot of applications in my web app and I see that grid component of ExtJS may fit in. However, I am not aware of what all things I can do with the - off the shelf available framework pieces - available plug-ins in the marketplace and - custom development through my own developers This is a typical question that we hear from the business users who wants to design an application by keeping the framework’s capability in perspective. In this article I have tried to put the list of stuff you can do with grid and hopefully that shall enable you to take advantage of the beauty of ExtJS. Pre-requisites This article assumes that you are familiar with basics of ExtJS What are the available options? In this section I will be taking you through some of the commonly seen usage of ExtJS grid panel. While covering all the capabilities of grid may not be possible, I am sure it will be helpful for the business users who want to

Ext4 Apply Store Filtering

In extjs4.1: There are many way for store filtering . Some of code i give here Filtering by single field: store . filter ( 'eyeColor' , 'Brown' );   Alternatively, if filters are configured with an  id , then existing filters store may be  replaced by new filters having the same  id . Filtering by single field: store . filter ( "email" , /\.com$/ );   Using multiple filters: store . filter ([ { property : "email" , value : /\.com$/ }, { filterFn : function ( item ) { return item . get ( "age" ) > 10 ; }} ]);   Using  Ext.util.Filter  instances instead of config objects (note that we need to specify the root config option in this case): store . filter ([ Ext . create ( ' Ext.util.Filter ' , {   property : "email" , value : /\.com$/ , root : 'data' }),   Ext . create ( ' Ext.util.Filter ' , {   filterFn : function ( item ) {   return item . get ( &

EXT JS 4: EMPTY VALUE IN A COMBOBOX

EXT JS 4: EMPTY VALUE IN A COMBOBOX Often, in an Ext JS combobox, it is difficult to go back to an empty value once you have selected an item, particularly if “forceSelection” is set to true.  Here is my roundup of alternative solutions found from around the web… 1. Override beforeBlur The solution from   http://www.sencha.com/forum/showthread.php?182119-How-To-Re-Empty-ComboBox-when-forceSelection-is-Set-To-TRUE  overrides beforeBlur on the combbox to clear out lastSelection.  Here is a copy of the override from the thread: 1 2 3 4 5 6 7 8 9 10 11 12 13 Ext.create( 'Ext.form.field.ComboBox' , {      ...      allowBlank: true ,      forceSelection: true ,      beforeBlur: function (){          var value = this .getRawValue();          if (value == '' ){              this .lastSelection = [];          }          this .doQueryTask.cancel();         this .assertValue();      } }); Or to apply the o