gabi
gabi

Reputation: 1376

ExtJS: insert value to added columns in a grid

I have a grid panel with 3 columns ['name', 'email', 'phone'], and it's model has 5 fields

['name', 'email', 'phone','property','value'].

What I'm looking for is to insert columns to the grid panel dynamically based on number of items in 'property' field and their values from 'value' field.

The sample code I'm working with is here.

My problem is that I don't know how to fill in data for new columns for each row.

Here is how the grid should look like in the end.

enter image description here

Upvotes: 2

Views: 1759

Answers (1)

Tyr
Tyr

Reputation: 2810

There are several things to do and there is room for improvements. I don't want to teach (or blame) you, so here is a working example based on your fiddle. I added comments to guide you whats happening there.

{
    text: 'add column',
    handler: function() {
        // Setup the columns, including the default ones
        var newColumns = [
            { header: 'Name',  dataIndex: 'name' },
            { header: 'Email', dataIndex: 'email', flex: 1 },
            { header: 'Phone', dataIndex: 'phone' }
        ];

        // Iterate through store items
        Ext.Array.each(Ext.data.StoreManager.lookup('simpsonsStore').data.items, function(storeItem) {

            // Create array from given strings in property/value fields
            var columns = storeItem.get('property') ? storeItem.get('property').split(' ').join('').split(',') : null;
            var columnValues = storeItem.get('value') ? storeItem.get('value').split(' ').join('').split(',') : null;

            // Iterate through the columns array
            for(var i = 0; i < columns.length; i++) {
                // Create new column
                var col = {
                    header: columns[i], 
                    dataIndex: columns[i]
                };

                // Check if column already added in the newColumns array
                var found = false;
                Ext.Array.each(newColumns, function(column) {
                    if (column.dataIndex == col.dataIndex)
                        found = true;
                });

                // Add column object if not found
                if (!found) {
                    newColumns.push(col);
                }

                // Edit the current store item to add the given value
                storeItem.set(columns[i], columnValues[i]);
            }
        });

        // Reconfigure columns on grid
        Ext.getCmp('gridpanel').reconfigure(Ext.data.StoreManager.lookup('simpsonsStore'), newColumns);

    }
}

Result:

enter image description here

Upvotes: 3

Related Questions