How to load a model with a custom ID Property

Today I Learned - How to load a model with a custom ID Property

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 `id`

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 `id`

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 `userId`

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

Want to learn more about Ext JS 6?

Ext-js-6-getting-started-trans

Ext JS 6: Getting Started is a new eBook that provides a practical guide to understanding and getting started with Sencha's Ext JS 6.

Enter your name and email address and I'll send you a 13 page sample chapter straight away!

I won't send you spam. Unsubscribe at any time.
Stuart Ashworth

I’m a software engineer, author and entrepreneur. I have spent the last 10 years creating things for mobile and web. I specialise in creating cross-platform HTML5 web and mobile applications using technologies such as JavaScript, Sencha and PhoneGap.