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]- Ext, Angular, React, and Vue - 27. June 2019
- The Site Resurgence - 11. February 2018
- Configuring ViewModel Hierarchy - 19. June 2015
2 Responses
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?
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
.