Using Calculated Fields in ExtJS and Sencha Touch

This is an archived post from the ExtJS era — the code may be obsolete, but the principles often still apply.

Calculated fields are fields that do not have their own values, but the values are calculated from the other fields of the same record. It is easiest to implement them in Model. For that:

  • add config: persist:false
  • implement convert function

In this example we concatenate First Name, space and Last Name to create a Full Name of the person.

Model Configuration

convert receives "value to convert"(v) and record as arguments. In this case we ignore the passed value entirely, because it is not needed to create the full name. Now we have only one little problem to solve: If you update first name or last name, for example in an editable grid, the full name is not updated. It is because convert method is called only if full name needs update. So one more override:

Here we override the default set method of the model. The override forces update of fullname always when any field is updated.

Using Calculated Fields in ExtJS and Sencha Touch Video

2 comments

  1. Patrick MuellerFebruary 10, 2015archive
    thanks for this example, saki (: is there a way to configure a convert / serialize method inside the model which I can use for multiple fields of the same type?
    1. SakiFebruary 10, 2015archive
      There are two main options: 1. You can extend a field to create a new type with the required convert/calculate implementation. See the source of Number field for example. Ext is doing this for all field types. This way you can use your custom field in any number of models. 2. You can create a global static class to hold all utility functions, convert/calculate functions, constants, etc. Then you can use a reference to that method in any field you want, e.g. <code>calculate:MyApp.Constants.myCalculate</code>.

Comments are closed on archived posts.