Blog.

Using Calculated Fields in ExtJS and Sencha Touch

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

    ,fields:[
         {name:'id', type:'int'}
        ,{name:'fname', type:'string'}
        ,{name:'lname', type:'string'}
        ,{name:'fullname', type:'string', persist:false,
            convert:function(v, record){
                var data = record.getData();
                return (data.fname ? data.fname + ' ': '') + data.lname;
            }}
        ,{name:'gender', type:'int'}
        ,{name:'totalContacts', type:'int', persist:false}
    ]

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.

[su_content_anon action=”want to see the solution and watch the demonstration video”] [/su_content_anon] [su_content_member] So one more override:

    ,set:function(name, value) {

        var o = {};
        if(Ext.isString(name)) {
            o[name] = value;
            name = o;
        }
        name.fullname = 'Hello';

        return this.callParent([name]);

    } // eo function set

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

[/su_content_member]
saki
Follow me:
Latest posts by saki (see all)

2 Responses

  1. 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. 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. calculate:MyApp.Constants.myCalculate.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Enter your username and password to log into your account. Don't have an account? Sign up.

Want to collaborate on an upcoming project?