0

I want to read json data from file - content of the json file shown below

    {
    "form": {
        "fields" : [
                {
                    "field":"textfield",
                    "name": "username",
                    "constrain": "5-10",
                    "value": ""
                },
                { 
                    "field":"textfield",
                    "name": "password",
                    "constrain": "5-10",
                    "value": ""
                },
                { 
                    "field":"datepickerfield",
                    "name": "Birthday",
                    "constrain": "5-10",
                    "value": "new Date()"
                },
                { 
                    "field":"selectfield",
                    "name": "Select one",
                     "options":[
                        {"text": "First Option",  "value": 'first'},
                        {"text": "Second Option", "value": 'second'},
                        {"text": "Third Option",  "value": 'third'}
                        ]
                },

            ]    
      }
}

Model

    Ext.define('dynamicForm.model.Form', {
        extend: 'Ext.data.Model',
        config: {
            fields: [
                {name: 'field', type: 'string'},
                {name: 'name', type: 'string'},
                {name: 'constrain', type: 'string'},
                {name: 'value', type: 'string'}
             ],
             hasMany: {model: 'dynamicForm.model.SelectOption', name: 'options'}
        }
    });

Ext.define('dynamicForm.model.SelectOption', {
    extend: 'Ext.data.Model',
    config: {
        fields: [
            {name: 'text', type: 'string'},
            {name: 'value', type: 'string'}
         ]
    }
});

store

Ext.define('dynamicForm.store.FormStore', {
    extend : 'Ext.data.Store',
    storeId: 'formStore',
    config : {
        model : 'dynamicForm.model.Form',
        proxy : {
            type : 'ajax',
            url : 'form.json',

            reader : {
                type : 'json',
                rootProperty : 'form.fields'
            }
        },
        autoLoad: true
    }
});

This what i tried so for.

    var fromval = Ext.create('dynamicForm.store.FormStore');
    fromval.load(function (){
        console.log(fromval);
              // i added register view which having form panel with id "testForm"
            Ext.Viewport.add({
                xtype : 'register'
            });
        for(i=0; i< fromval.getCount(); i++) {
            console.log("------");
            Ext.getCmp('testForm').add({
                    xtype: fromval.getAt(i).data.field,
                    label: fromval.getAt(i).data.name,
                    value: fromval.getAt(i).data.value,
                    options: [
                        {text: "First Option",  value: "first"},
                        {text: "Second Option", value: "second"},
                        {text: "Third Option",  value: "third"}
                    ]
            });
        }
    });

two text fileds and date are woking good, but i don't know how to get options for select field from store, just heard coded now.

over all Based on the above json data, i need to create sencha form dynamically.

5
  • @TDeBailleul i can't find any post related to my question in that website. Commented Mar 6, 2013 at 10:51
  • No there is nothing related to your question. But have you read the article ? From the article: "If you’re a developer and you’re about to ask another developer a technical question (on a forum, via email, on a chat channel, or in person), you’d better be ready to answer the question “What have you tried?” [...] The problem is that this person’s problem-solving technique is to ask for the solution. Not to seek advice on how to approach the task but to just ask for the code, fully formed and ready to go" Commented Mar 6, 2013 at 11:50
  • @TDeBailleul i never look for ready code in stack overflow, i just want an idea and i am trying Commented Mar 6, 2013 at 12:19
  • Ok then, do you have access to the JSON ? Can you modify it before it is sent/retrieved ? Commented Mar 6, 2013 at 16:46
  • 1
    @TDeBailleul, i updated what i tried Commented Mar 7, 2013 at 11:17

3 Answers 3

1

Better to follow MVC structure:

Create a model:

Ext.define('MyApp.model.FormModel', {
extend: 'Ext.data.Model',
config: {
    fields: ["field","name"]
}
});

A store with proxy:

Ext.define('MyApp.store.FormStore',{
extend: 'Ext.data.Store', 
config:
{
    model: 'MyApp.model.FormModel',
    autoLoad:true,
    proxy:
    {
        type: 'ajax',
        url : 'FormData.json', //Your file containing json data
        reader:
        {
                rootProperty:'form.fields'
        }
    }
}
});

The formData.json file:

{
"form": {
    "fields" : [
            {
                "field":"textfield",
                "name": "username"
            },
            { 
                "field":"textfield",
                "name": "password"
            },
        ]    
  }
}

And then use the FormStore to fill the form data as you need.

Ext.define('MyApp.view.LoginPage', {
extend: 'Ext.form.Panel',
config: {
items:{
xtype:'fieldset',
layout:'vbox',
items:[{
        flex:1,
        xtype:'textfield',
        id:'namefield',
        placeHolder:'Username'
    },{
        flex:1,
        xtype:'passwordfield',
        id:'passwordfield',
        placeHolder:'Password'
    }]
},
listeners:{
    painted:function()
    {
        var store=Ext.getStore('FormStore');
        while(!store.isLoaded())
        {
            console.log("loading...");
        }

        var record=store.getAt(0);
        Ext.getCmp('namefield').setValue(record.data.name);
        Ext.getCmp('passwordfield').setValue(record.data.password);
    }
}
}
});
Sign up to request clarification or add additional context in comments.

4 Comments

+1 Thanks @Malay Shah, i did exactly same and i can get the fields value from store, now i am trying to add field dynamically to from panel which is already created and i am not successful yet.
This might help, though little out of track. stackoverflow.com/questions/11616286/… specifically, you could have options property as empty {} in first 3 items.
how to get options property from form model
var opt= formval.getAt(i).raw.options; if(opt) { console.log(opt); } It logs, couldn't figure out a proper way yet though.
1
{
    "data":[
        {
            "xtype":"textfield",
            "title":"UserName",
            "name": "username"
        },
        { 
            "xtype":"textfield",
            "title":"password",
            "name": "password"
        },
        { 
            "xtype":"textfield",
            "title":"phone no",
            "name": "birthday"
        },
        { 
            "xtype":"textarea",
            "title":"address",
            "name": "address"
        }
    ]
}

Ext.define('dynamicForm.model.FormModel', {
        extend: 'Ext.data.Model',

        fields: ['field', 'name']
    });


Ext.define('dynamicForm.store.FormStore', {
    extend : 'Ext.data.Store',
    model : 'dynamicForm.model.FormModel',
    proxy : 
    {
        type : 'ajax',
        url : 'data/user.json',

        reader : 
        {
            type : 'json',
            rootProperty:'data'
        },

        autoLoad: true
    }
});


Ext.define('dynamicForm.view.DynaForm',{
    extend:'Ext.form.Panel',
    alias:'widget.df1',

    items:[]

});

Ext.application({
    name:'dynamicForm',
    appFolder:'app',

    controllers:['Users'],

    launch:function(){
        Ext.create('Ext.container.Viewport',{

            items:[
                {
                    xtype:'df1',

                    items:[]
                }
            ]
        });
    }
});

Ext.define('dynamicForm.controller.Users',{
    extend:'Ext.app.Controller',

    views:['DynaForm'],
    models:['FormModel'],
    stores:['FormStore'],

    refs:[
    {
        ref:'form1',
        selector:'df1'
    }
    ],

    init:function(){
        console.log('in init');
        this.control({
            'viewport > panel': {
                render: this.onPanelRendered
            }
        });
    },

    onPanelRendered: function() {

        var fromval=this.getFormStoreStore();
        var form=this.getForm1();
        fromval.load({
            scope: this,
            callback: function(records ,operation, success) {
                Ext.each(records, function(rec) {
                 var json= Ext.encode(rec.raw);
                 var response=Ext.JSON.decode(json);
                 for (var i = 0; i < response.data.length; i++) {
                    form.add({
                        xtype: response.data[i].xtype,
                        fieldLabel: response.data[i].title,
                        name: response.data[i].name
                        });
                    }
                    //form.add(Ext.JSON.decode(json).data);
                    form.doLayout();
                });
            }
        });
    }
});

Comments

-1

It will be done automatically if you insert it into any extjs component content :

var jsonValues =  "{
    "form": {
        "fields" : [
                {
                    "field":"textfield",
                    "name": "username"
                },
                { 
                    "field":"textfield",
                    "name": "password"
                },
            ]    
      }
}";

var panel = new Ext.Panel({
        id        : 'myPanel',
        items      : [jsonValues]
});

panel.show();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.