Wednesday 3 July 2013

Select dropdown with dynamic values in Sencha Touch 2

Today, we are going to see how to display drop down field with dynamic Time Zone values in Sencha Touch 2.

Create a Time Zone Model

First, let's create a Time Zone model with two fields name and value using fields configuration.
Ext.define('MyApp.model.TimeZoneModel', {
    extend: 'Ext.data.Model',
    alias: 'model.TimeZoneModel',

    config: {
        fields: [{
            name: 'name',
            type: 'string'
        }, {
            name: 'value',
            type: 'string'
        }]
    }
});

Create a Time Zone Store

Now, we are going to create a Time Zone Store and associate the above model to the store using model Configuration. Then, we are going to assign static time zone array data using data configuration. you can also load this time zone array data from json file using store reader configuration.
Ext.define('MyApp.store.TimeZoneStore', {
    extend: 'Ext.data.Store',
    alias: 'store.TimeZoneStore',

    requires: [
        'MyApp.model.TimeZoneModel'
    ],

    config: {
        autoLoad: true,

        data: [{
            name: '--Please Select--',
            value: ''
        }, {
            name: 'America Chicago',
            value: 'America/Chicago'
        }, {
            name: 'America Jamaica',
            value: 'America/Jamaica'
        }, {
            name: 'America Mexico City',
            value: 'America/Mexico_City'
        }, {
            name: 'America New York',
            value: 'America/New_York'
        }, {
            name: 'America Panama',
            value: 'America/Panama'
        }, {
            name: 'America Port of Spain',
            value: 'America/Port_of_Spain'
        }, {
            name: 'America Los Angeles',
            value: 'America/Los_Angeles'
        }, {
            name: 'America Guyana',
            value: 'America/Guyana'
        }],

        model: 'MyApp.model.TimeZoneModel',
        storeId: 'TimeZoneStore'
    }
});

Create Select drop down field

Now, we are going to assign the above store to the Select drop down field using store configuration. displayField configuration will be mapped to the model field name and valueField configuration will be mapped to the model field value.
Ext.define('MyApp.view.FormPanel', {
    extend: 'Ext.form.Panel',
    alias: 'widget.FormPanel',

    config: {
        items: [{
            xtype: 'toolbar',
            docked: 'top',
            title: 'Dynamic Select Demo'
        }, {
            xtype: 'selectfield',
            label: 'Select Time Zone',
            labelWrap: true,
            required: true,
            displayField: 'name',
            valueField: 'value',
            store: 'TimeZoneStore'
        }]
    }
});

Following is the output, when i run the above code in Google Chrome



Hope, you enjoyed this Post.

No comments:

Post a Comment