ExtJs 4 - avoid adding duplicate records

This is quick tip on how to avoid adding duplicate records to data store in ExtJs 4.

In my example I have Ext.grid.Panel which dynamically creates store for itself in constructor method from provided list of fields:

 

this.store = Ext.create('Ext.data.Store', {
	fields: fields,
	data: data,
	proxy: {
		type: 'memory',
		reader: {
			type: 'json',
			root: 'items'
		}
	}
});

for easy access to store fields definition I have created extra parameter for my references:

this.storeFields = fields;

 

I think easiest solution is to use "filters"... 

To make dynamic for store

You can create or use this function:

 

checkIfRecordExists: function(rec){
		var filtersArray = [];
		for(var i = 0; i < this.storeFields.length; i++){
			var f = this.storeFields[i];
    		if(f != 'feature'){
    			// create dynamically set of filters - for all record columns
    			// this way we make sure there are no duplicates
    			var filter = Ext.create('Ext.util.Filter', {property: f, value: rec[f], root: 'data'});
    			filtersArray.push(filter);
    		}
    	}
    	console.warn('store before filter', this.store.getCount(), this.store);
    	this.store.filter(filtersArray);
    	console.warn('store after filter', this.store.getCount(), this.store);
    	if(this.store.getCount() > 0){
    		return true;
    	}
    	return false;
    }
blog comments powered by Disqus