Getting displays for IDs in EXT-JS

Here’s a tip I’ve found quite useful:

When displaying an asynchronously loaded set of objects, the objects may have IDs for reference information instead of the reference object itself. For example, if viewing a list of Cities, which have been filtered by State, the city object may contain a state_id, not a State object. To display the state name, you would either retrieve the State afterwards or modify your transfer object to carry the State. But here is a third option — get the State name from the filter combobox!

To get the display of a record by its value, add the following method to the ComboBox:

{
  xtype: "combobox", // form object type
  emptyText: "State", // text to show user what this dropdown is
  id: "state-filterDD", // id to get this combobox elsewhere
  store: {
    // store info
    valueField: "id", // field on the object
    displayField: "name", // field on the object
    getDisplay: function (value) {
      var display = null;
      this.getStore().each(function (rec, idx) {
        if (rec.data["id"] == value) {
          display = rec.data["name"];
        }
      });
      return display;
    },
  },
}

This method takes the state_id, and loops through the combobox’s options to find the record with that ID. Then it returns the display. To modify this, you can revise the ‘id’ and ‘name’ properties being accessed to that of your object in the model of the combobox’s store.

And to use, assuming you have a renderer on your GridPanel, use:

return Ext.getCmp('state-filterDD').getDisplay(stateId);