How to load a model with a custom ID Property

— 2 minute read


Ext JS Models (Ext.data.Model class) defaults to having an ID property named id. This field will be automatically created for you and be mapped to the id field in your incoming data. By knowing where the unique key for the model lies we can make use of some handy methods on the model, such as getId, and findById on an Ext.data.Store instance.

In this snippet we can see that 3 fields are created - our two explicit fields, and the automatically created id field.

Screenshot of DevTools showing a console log of an array with 3 field items

However, our data will often use an ID field that isn't id (e.g. userId) and so we have to tell the model which field to use instead. We do this simply by setting the idProperty config when defining our model.

With this config in place we see that only 2 fields are created.

Screenshot of DevTools showing a console log of an array with 2 field items

Loading Model Data

With every Ext.data.Model class definition we can use its static load method to load in data for a specific ID. If we take our first example, which uses the default id field, and call the User.load method with an ID of 1 we can see the AJAX call passes a parameter named id with a value of 1. No surprises there, our server would use this to lookup the data and send it back.

Screenshot of DevTools showing an AJAX request with a param of

Now let's take our second example, which has the idProperty set to userId, and call the User.load method again.

Screenshot of DevTools showing an AJAX request with a param of

I would have expected the parameter that is sent to the server to use the idProperty name (userId) but instead the default of id is still sent - not ideal when our server expects userId!

To get around this we need to add a config to the proxy - idParam. This works in a similar way to idProperty and tells the proxy which field and name to use when dealing with IDs.

Screenshot of DevTools showing an AJAX request with a param of

Now if we look at the AJAX call made it passes a userId value.

Filed under