Virtual Fields in Sencha Touch Models

I wanted to display a user’s full name in a Sencha Touch Select control. I figured this would be as easy as defining a template for the control.

// this doesn't work{    xtype: 'selectfield',    label: 'Name',    store: store,    valueField: 'id',    tpl: '{firstName} {lastName}'}

Unfortunately, that didn’t work.

Next I decided to create a fullName() function my model.

Ext.regModel('Person', {    fields: [        {name: 'id', type: 'int'},        {name: 'firstName', type: 'string'},        {name: 'lastName', type: 'string'}    ],    fullName: function() {        return this.data.firstName + " " + this.data.lastName;    }});

The function worked great, but not in the Select control. Select#displayField expects a field name and won’t call a function.

I needed to create a virtual field in the model. I couldn’t find any documentation for this, but Rich Waters offered a solution via the Sencha Touch Forums.

Ext.regModel('Person', {    fields: [        {name: 'id', type: 'int'},        {name: 'firstName', type: 'string'},        {name: 'lastName', type: 'string'},        {name: 'fullName', type: 'string',            convert: function(v, rec) {                return rec.data.firstName + " " + rec.data.lastName;            }        }    ]});

Once the virtual model field was created, I could use it in the select control.

{    xtype: 'selectfield',    label: 'Name',    store: store,    valueField: 'id',    displayField: 'fullName'}

For a full example see http://github.com/don/sencha-virtual-model-field

Advertisements
Tagged with: ,
Posted in Uncategorized
2 comments on “Virtual Fields in Sencha Touch Models
  1. Anonymous says:

    Hi Don and thank you for this entry. You just saved me probably an hour or more of head scratching :)Thanks

  2. psenough says:

    thanks for the post! was looking for something else but this ended up being quite interesting read and i did apply the knowledge learned to cook some parsers which helped clean up my code :) so cheers!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: