
Background:
By default, when you add a new row to a data grid like FlexGrid, the new row is empty. Often developers want newly added rows to come pre-populated with default values. FlexGrid makes this easy by using the newItemCreator property of its CollectionView, which allows you to specify a function that returns the default values for each newly created item.
Steps to Complete:
- Create a CollectionView and assign it as the grid’s itemsSource.
- Bind the CollectionView to FlexGrid.
- Use newItemCreator on the CollectionView to define default values for newly added rows.
Getting Started:
Create a CollectionView and assign it as the grid’s itemsSource
A CollectionView wraps your data and provides hooks such as newItemCreator. Setting allowAddNew to true enables the grid’s built-in new-row template so users can add rows through the UI.
import * as wjcCore from '@mescius/wijmo';
const items = new wjcCore.CollectionView(getData(10), {
newItemCreator: () => ({
id: getNextId(),
country: 'Default Country',
discount: 0,
downloads: 0,
sales: 0,
expenses: 0
})
});
Bind the CollectionView to FlexGrid
This assigns the CollectionView to the grid and enables row creation via the UI.
<wj-flex-grid
:itemsSource="items"
:allowAddNew="true"
/>
- When the user begins editing the new-row template, FlexGrid calls newItemCreator to generate the default row values.
Use newItemCreator on the CollectionView to define default values for newly added rows
The newItemCreator function returns a plain object that becomes the data for the new row. These values appear immediately when the row is created.
function getNextId() {
const arr = items.sourceCollection;
return Math.max(0, ...arr.map(item => item.id)) + 1;
}
File for Reference
<template>
<wj-flex-grid
:itemsSource="items"
:allowAddNew="true"
/>
</template>
<script>
import * as wjcCore from '@mescius/wijmo';
import { WjFlexGrid } from '@mescius/wijmo.vue2.grid';
export default {
components: { WjFlexGrid },
data() {
return {
items: null
};
},
created() {
this.items = new wjcCore.CollectionView(getData(10), {
newItemCreator: () => ({
id: this.getNextId(),
country: 'Default Country',
discount: 0,
downloads: 0,
sales: 0,
expenses: 0
})
});
},
methods: {
getNextId() {
const arr = this.items.sourceCollection;
return Math.max(0, ...arr.map(i => i.id)) + 1;
}
}
};
function getData(count) {
return Array.from({ length: count }, (_, i) => ({
id: i + 1,
country: 'Country ' + (i + 1),
discount: 0,
downloads: 0,
sales: 0,
expenses: 0
}));
}
</script>
With this Vue setup, any newly added row, whether added through the UI or programmatically, will be initialized with your predefined default values. This improves usability and ensures consistent data entry.
Happy coding!
Andrew Peterson