ExtJs: Как генерировать динамические или общие поля данных? - PullRequest
0 голосов
/ 11 сентября 2018

Как я могу генерировать динамические поля формы? В настоящее время данные загружаются из файла JSON через viewModel. Затем он связывается с некоторыми полями данных панели, такими как мой пример и текущее состояние ниже:

Configuration.json -> будет расширен с большим количеством записей

{
    "configuration": [
      {
        "name": "firstargument",
        "value": "123",
        "type": "string"
      } //I would like to extend that file later with more different data fields and data types
    ]
  }

ViewModel: Configuration.js -> здесь нужно как-то загрузить несколько записей

Ext.define('QuickApp.model.Configuration', {
    extend: 'Ext.app.ViewModel',

    alias: 'viewmodel.configuration',

    data: {
        name: '', //here I need a data set with multiple entries
        value: ''
    },

    constructor: function(config) {
        var vm = this;

        this.callParent(arguments);

        vm.setStores({
            info: {
                fields: ['name','value'],
                proxy: {
                    type: 'ajax',
                    url: 'app/Configuration.json',
                    reader: {
                        tyoe: 'json',
                        rootProperty: 'configuration'
                    }
                },
                autoLoad: true,
                listeners: { //Or maybe some for each magic here? I don't know the syntax...
                    load: function(store, records) {
                        vm.set('name', store.getAt(0).get('name'));
                        vm.set('value', store.getAt(0).get('value'));
                    }
                }
            }
        });
    }
 });

Configurationplugin.js -> Как создать здесь несколько динамических / универсальных дочерних элементов?

Ext.define('QuickApp.view.configurationplugin.Configurationplugin',{
    extend: 'Ext.form.Panel',
    alias: 'widget.configurationplugin',

    title: 'Configuration Plugin',
    modal: true,
    draggable: true,
    floating: true,
    bodyPadding: 10,
    width: 300,
    centered: true,

    viewModel: {
        type: 'configuration'
    },

    items: [{
        xtype: 'textfield', //and how can I add multiple childs then here depending on the given types?
        name: 'firstargument',
        bind:{
            label: '{name}',
            value: '{value}',
        },
    }, {
        xtype: 'toolbar',
        docked: 'bottom',
        items: ['->', {
            xtype: 'button',
            text: 'Submit',
            iconCls: 'x-fa fa-check',
            handler: function() {
                this.up('configurationplugin').destroy();
            }
        }, {
            xtype: 'button',
            text: 'Cancel',
            iconCls: 'x-fa fa-close',
            handler: function() {
                this.up('configurationplugin').destroy();
            }
        }],
    }],
});

Я знаю, это много кода. Но я был бы благодарен за любые подсказки! Текущий код работает нормально, только с одними данными. Большое спасибо!

1 Ответ

0 голосов
/ 11 сентября 2018

Вы можете использовать initialize событие для formpanel и add() для добавления компонента на основе типа.

Вы можете напрямую добавить компонент, передать конфигурацию как name или label. И вы также можете использовать binding.

Вы можете проверить здесь с рабочим Скрипка

КОД SNIPPET

Ext.application({
    name: 'Fiddle',

    launch: function () {

        Ext.create('Ext.data.Store', {
            fields: ['name', 'value'],
            storeId: 'configuration',
            proxy: {
                type: 'ajax',
                url: 'Configuration.json',
                reader: {
                    tyoe: 'json',
                    rootProperty: 'configuration'
                }
            },
            autoLoad: true
        })

        Ext.define('QuickApp.model.Configuration', {
            extend: 'Ext.app.ViewModel',

            alias: 'viewmodel.configuration'
        });

        Ext.define('QuickApp.view.configurationplugin.Configurationplugin', {
            extend: 'Ext.form.Panel',
            alias: 'widget.configurationplugin',

            title: 'Configuration Plugin',

            modal: true,

            draggable: true,

            floating: true,

            bodyPadding: 10,
            width: 300,
            centered: true,

            viewModel: {
                type: 'configuration'
            },

            listeners: {
                initialize: function () {

                    var me = this,
                        items = [],
                        xtypes = {
                            'string': 'textfield',
                            'number': 'numberfield'
                        },
                        vm = me.getViewModel();

                    Ext.getStore('configuration').each(rec => {
                        let name = rec.get('name'),
                            value = name + 'Value';

                        items.push({
                            xtype: xtypes[rec.get('type')],
                            bind: {
                                label: `{${name}}`,
                                value: `{${value}}`,
                                name: `{${name}}`
                            }
                        });
                        vm.set({
                            [name]: name, [value]: rec.get('value')
                        })
                    });

                    /*
                    You colud direcly add like this without binding
                    items.push({
                        xtype: xtypes[rec.get('type')],
                        label:name,
                        value:rec.get('value')
                        name:name
                    });*/

                    items.push({
                        xtype: 'toolbar',
                        docked: 'bottom',
                        items: ['->', {
                            xtype: 'button',
                            text: 'Submit',
                            iconCls: 'x-fa fa-check',
                            handler: function () {
                                this.up('configurationplugin').destroy();
                            }
                        }, {
                            xtype: 'button',
                            text: 'Cancel',
                            iconCls: 'x-fa fa-close',
                            handler: function () {
                                this.up('configurationplugin').destroy();
                            }
                        }]
                    })
                    this.add(items)
                }
            }
        });

        Ext.create({
            xtype: 'container',
            fullscreen: true,
            items: [{
                xtype: 'button',
                margin: 5,
                ui: 'action',
                text: 'Create form',
                handler: function (btn) {
                    Ext.create({
                        xtype: 'configurationplugin',
                    }).showBy(btn);
                }
            }]
        });
    }
});
...