Checking for existing value in Grid Panel in ExtJS - extjs

So if I have a gridpanel in ExtJS 4, how do I check for a value in it?
I'm building a pop-up window to add a value to the gridpanel, and I want to make sure that the value the user is trying to add to the gridpanel isn't already listed in the grid panel.
I've been searching the docs for a while and googling around and haven't found anything.

I added the following code to the bottom of the example at http://dev.sencha.com/deploy/ext-4.0.7-gpl/examples/grid/array-grid.html
Hopefully it's a start for you, though you might have additional things to consider such as the following in order to devise the most robust solution:
What if the same value can occur multiple times in the grid?
What if the data in the grid is paginated?
CODE:
dockedItems: [{
xtype: 'toolbar',
items : [ {
xtype: 'button',
text: 'Seek Value',
handler: function() {
Ext.Msg.prompt('Value in Grid?', 'Search:', function(btn, text){
if (btn == 'ok' && text){
var columnNames = Ext.Array.pluck(grid.columns, 'dataIndex');
grid.store.data.each(function(record, index) {
for (var i=0,n=columnNames.length; i<n; i++) {
var columnName = columnNames[i];
if (columnName) { //protects against null dataIndex using pluck above
if (record.get(columnName) == text) {
console.log(index); //row
console.log(columnName);
return;
}
}
}
});
}
});
}
}],
dock: 'bottom'
}]

Related

How does an end user clear the sorting for a grid column?

I use ExtJs 6.6.0 Classic. The grid component supports multi-column sorting (I use remoteSort: true, remoteFilter: true). Whenever the user clicks on a column header, that column becomes the first column in the order by list. But I cannot find how an end user is supposed to clear the sorting for a column. The context menu available through the column header doesn't have a "Clear Sort" option.
See also this kitchensink example.
I feel like I am missing something. There is a sortClearText config for the column inherited from the header, but I could not find a place where it's used (I thought that perhaps there is some config I can use to add the Clear Sort menu item to the column context menu).
I could add a button to execute the action of clearing the sorting of the store, as a last resort, but I don't like it.
Is there a simple way to add a Clear Sort option for a grid column through the Extjs components configuration?
Thank you
I also did not find, but you can use the following override:
Ext.define('overrides.grid.header.Container', {
override: 'Ext.grid.header.Container',
getMenuItems: function() {
var me = this,
menuItems = [],
hideableColumns = me.enableColumnHide ? me.getColumnMenu(me) : null;
if (me.sortable) {
menuItems = [{
itemId: 'ascItem',
text: me.sortAscText,
iconCls: me.menuSortAscCls,
handler: me.onSortAscClick,
scope: me
}, {
itemId: 'descItem',
text: me.sortDescText,
iconCls: me.menuSortDescCls,
handler: me.onSortDescClick,
scope: me
}, {
itemId: 'dropSortItem',
text: me.sortClearText,
//iconCls: me.menuSortDescCls, // Your icon
handler: me.onSortClearClick,
scope: me
}];
}
if (hideableColumns && hideableColumns.length) {
if (me.sortable) {
menuItems.push({
itemId: 'columnItemSeparator',
xtype: 'menuseparator'
});
}
menuItems.push({
itemId: 'columnItem',
text: me.columnsText,
iconCls: me.menuColsIcon,
menu: hideableColumns,
hideOnClick: false
});
}
return menuItems;
},
onSortClearClick: function() {
var menu = this.getMenu(),
activeHeader = menu.activeHeader,
store = this.up('grid').getStore();
store.getSorters().each(function(sorter) {
if(sorter.initialConfig.property == activeHeader.dataIndex) {
store.getSorters().remove(sorter)
}
}, this);
}
});

EXTJS Spreadsheet Model - Keep row number column, but hide actual row numbers

I can't seem to figure out how to do this and google has been no help. I am using the ExtJS Spreadsheet model. I am trying to show the column with the row numbers, but I want to remove/hide the actual row numbers. I only want to keep the column that contain the row numbers. Any ideas on how I might go about doing this?
That should be easily done. As with every column, you have to add a custom renderer to the rownumberer column. So how do you get to that column?
For this, the spreadsheet selModel has a function getNumbererColumnConfig which you want to override. The unoverridden function from sources:
getNumbererColumnConfig: function() {
var me = this;
return {
xtype: 'rownumberer',
width: me.rowNumbererHeaderWidth,
editRenderer: ' ',
tdCls: me.rowNumbererTdCls,
cls: me.rowNumbererHeaderCls,
locked: me.hasLockedHeader
};
},
so, to override, you would do the following:
selModel: {
type: 'spreadsheet',
// Disables sorting by header click, though it will be still available via menu
columnSelect: true,
pruneRemoved: false,
extensible: 'y',
getNumbererColumnConfig: function() {
var me = this;
return {
xtype: 'rownumberer',
width: me.rowNumbererHeaderWidth,
renderer:function() { return ' '; },
editRenderer: ' ',
tdCls: me.rowNumbererTdCls,
cls: me.rowNumbererHeaderCls,
locked: me.hasLockedHeader
};
}
},
Tested in a Sencha fiddle

change the background color of panels in extjs

In my project, I am trying to change the background color of all the panels inside a container. The code which I am trying is as follows:
container --> panel (don't change) --> panel (Change)
//Generated dynamically using for loop.
listeners: {
'render': function(panel) {
panel.body.on('click', function() {
//here change the background color of all the panels inside the container>panel.
});
}
}
What should I write to change the background color of the only panels which are present inside the parent panels of a main container?
I tried:
Ext.each('panel',function(){this.body.setStyle('background','white')}),
But the above approach is giving me the following error:
Uncaught TypeError: Cannot call method 'setStyle' of undefined
EDIT:
Here, I am looking for a method of extjs which quite do the same work as jQuery's children().
$('#containerID').children('panel').children('panel').css(change background color);
Based on your requirements you will always have a sum of 9 components you are looking at -1 the you start from. The shortest way is to use the each() method of the MixedCollection (at runtime all items are within a MixedCollection)
'render': function(panel) {
panel.body.on('click', function() {
panel.items.each(function(p){ p.body.setStyle('background','white'); }, this)
},this);
}
This may not be the variant with the best performance but knowing your requirement from the last question I can say that this is the easiest. And in addition it will be easy to maintain. And read the article about delegates that I posted in the comments of the last question!
I hope there is now typo, cause it is untested
Update
Well, you are looking for the ownerCt property here (at least that is the easiest way). But there are some mightier navigation methods up() / down() both can be feeded with a ComponentQuery string. Leave the up() arguments empty will return the immediate owner/activater (basically the same as ownerCt).
Following a working example:
var childItems = [], items = [];
for (i = 0; i < 9; ++i) {
childItems.push({
xtype: 'container',
width: 50,
height: 50,
html: i + '',
style: {borderColor:'#000000', borderStyle:'solid', borderWidth:'1px'},
listeners: {
'afterrender': function(panel) {
panel.el.on('click', function(e,t) {
panel.el.on('click', function(e,t) {
panel.el.setStyle('background','red');
panel.ownerCt.items.each(function(p){ if(panel.el.id != p.id) p.el.setStyle('background','white'); })
});
}
}
});
}
for (i = 0; i < 9; ++i) {
items.push({
xtype: 'container',
layout: {
type: 'table',
columns: 3
},
style: {borderColor:'#000000', borderStyle:'solid', borderWidth:'1px'},
items: childItems
});
}
Ext.create('Ext.container.Container', {
layout: {
type: 'table',
// The total column count must be specified here
columns: 3
},
renderTo: Ext.getBody(),
style: {borderColor:'#000000', borderStyle:'solid', borderWidth:'1px', margin: '30px'},
items: items
});
Update 2
To reset all try this (untested)
'afterrender': function(panel) {
panel.el.on('click', function(e,t) {
panel.el.setStyle('background','red');
panel.ownerCt.ownerCt.items.each(function(op){
op.items.each(function(p){
if(panel.el.id != p.id)
p.el.setStyle('background','white');
})
}, this)
});
}
JSFiddle

Apply grid filter programmatically from function

Using Ext.ux.grid.FiltersFeature, I have remote filters and I am trying to write a function to apply a date filter on a grid column programmatically (rather than clicking on the filter drop down menu in the column header). The first time I run the function the grid store gets reloaded without the filter. When I run the function a second time (and every time thereafter) it works totally fine, the store reloads with the filters. Here is the gist of the function I have:
// a filter object for testing
aFilter = {type: 'date', field: 'a_date_field', comparison: 'gt', value: '2012-03-08 00:00:00'}
var grid = Ext.create('Ext.grid.Panel', {
store: store,
features: [{
ftype: 'filters',
}],
columns[{
header: 'ID',
dataIndex: 'id',
itemId: 'id',
width: 40,
}, {
xtype: 'datecolumn',
header: 'Date',
dataIndex: 'a_date_field',
itemId: 'a_date_field',
width: 75,
format:'j-M-Y',
filterable: true
}],
listeners: {
'afterrender': function() {
// Need to create the filters as soon as the grid renders
// rather than waiting for the user to click on the header
grid.filters.createFilters();
}
},
bbar: [{
text: 'Do a filter',
handler: function() {
// get the filter that is attached to the grid
var gridFilter = grid.filters.getFilter(aFilter.field);
// have to do this to create a menu for this filter
gridFilter.init({dataIndex: aFilter.field, type: aFilter.type, active: true});
// if this column is a date filter column
if (gridFilter.type == 'date') {
var dateValue = Ext.Date.parse(aFilter.value, 'Y-m-d H:i:s');
if (filter.comparison == 'gt') {
gridFilter.setValue({after: dateValue});
} else {
gridFilter.setValue({before: dateValue});
}
}
}
}
});
I also found that this function works the first time if I click on any grid header menu before I run the function.
I've been trying to find out what changes are made to the grid which make the filter work after the first attempt fails or what clicking on any grid header does to make it work. But nothing I add seems to fix it so it will run the first time. Has anyone implemented this successfully?
I have workaround:
bbar: [{
text: 'Do a filter',
handler: function() {
var grid = this.up('grid');
var dateValue = Ext.Date.parse(aFilter.value, 'Y-m-d H:i:s');
var value = aFilter.comparison == 'gt' ? {after: dateValue} : {before: dateValue};
var gridFilter = grid.filters.getFilter(aFilter.field);
if (!gridFilter) {
gridFilter = grid.filters.addFilter({
active: true,
type: aFilter.type,
dataIndex: aFilter.dataIndex,
});
gridFilter.menu.show();
gridFilter.setValue(value);
gridFilter.menu.hide();
} else {
gridFilter.setActive(true);
}
Ext.Function.defer(function(){
gridFilter = grid.filters.getFilter(aFilter.field);
gridFilter.setValue(value);
}, 10);
}
}]
As you can see I actually apply filter 2 times.
As an update, I expanded this function and modified it to work with ExtJS 4.1.1
Here is an example of the function to set grid filters dynamically (without the user needing to click on the menu items). Afterwards, the filtered items will be visible to the user in the grid column header menus as if he clicked on them and set them manually.
The "grid" argument is a grid with FiltersFeature that you want to filter. The other argument is an array of "filter" objects (I'll show an example below), the function simply applies all the passed "filter" objects to the grid.
doGridFilter: function(grid, filters) {
// for each filter object in the array
Ext.each(filters, function(filter) {
var gridFilter = grid.filters.getFilter(filter.field);
gridFilter.setActive(true);
switch(filter.data.type) {
case 'date':
var dateValue = Ext.Date.parse(filter.data.value, 'm/d/Y'),
value;
switch (filter.data.comparison) {
case 'gt' :
value = {after: dateValue};
break;
case 'lt' :
value = {before: dateValue};
break;
case 'eq' :
value = {on: dateValue};
break;
}
gridFilter = log.filters.getFilter(filter.field);
gridFilter.setValue(value);
gridFilter.setActive(true);
break;
case 'numeric':
var value;
switch (filter.data.comparison) {
case 'gt' :
value = {gt: filter.data.value};
break;
case 'lt' :
value = {lt: filter.data.value};
break;
case 'eq' :
value = {eq: filter.data.value};
break;
}
gridFilter = log.filters.getFilter(filter.field);
gridFilter.setValue(value);
gridFilter.setActive(true);
break;
case 'list':
gridFilter = log.filters.getFilter(filter.field);
gridFilter.menu.setSelected(gridFilter.menu.selected, false);
gridFilter.menu.setSelected(filter.data.value.split(','), true);
break;
default :
gridFilter = log.filters.getFilter(filter.field);
gridFilter.setValue(filter.data.value);
break;
}
});
}
Here's an example of a "filter" object array.
// an example of a "filters" argument
[{
field: 'some_list_column_data_index',
data: {
type: 'list',
value: 'item1,item2,item3,item4,item5,item6,item7'
}
}, {
field: 'some_date_column_data_index',
data: {
type: 'date',
comparison: 'gt',
value: '07/07/2007'
}
}]
One caveat, you need to "create" the filters manually before using this function. Normally FiltersFeature grid filters are "created" the first time a user clicks on one of them, that may not happen if the user just wants to apply one of these predefined filters.
That can be handled easily by including this afterrender listener in the gridpanel.
listeners: {
// must create the filters after grid is rendered
afterrender: function(grid) {
grid.filters.createFilters();
}
}
Just add
filter: true
to grid columns description like this:
me.columns = [
{header:"Name", dataIndex:"name", editor:"textfield", filter: true},
];
if you want to get the filter work after the first attempt, first instance create.
Here is something that may be worth looking into. It seems that the filters plugin is listening for menucreate event to initialize the filters. I wonder if menu create event is deferred until necessary and hence the filters don't get initialized?
/**
* #private Handle creation of the grid's header menu. Initializes the filters and listens
* for the menu being shown.
*/
onMenuCreate: function(headerCt, menu) {
var me = this;
me.createFilters(); //<------
menu.on('beforeshow', me.onMenuBeforeShow, me);
},
Do you want to apply grid filter or may be store.filter() capability would suit you better? In this case just filter the store, and grid will display filtered records.
I discovered another way to implement this. It appears that grid features are only bound to the grid after the grid is rendered. This means that any setup of the filter will not take effect until after the grid is rendered. The initial load of the store appears to be initiated before the grid is rendered.
I solved my problem by creating my store with a memory proxy containing no data.
me.store = Ext.create('Ext.data.Store', {
model: 'SummaryData',
data: [],
proxy: {
type: 'memory',
reader: 'array'
},
remoteSort: true,
remoteFilter: true
});
Then set up an afterrender handler on the grid to poke in the correct proxy and initiate a load of the store.
afterrender: function () {
var me = this;
me.store.setProxy({
type: 'ajax',
url : '/print_unallocated/change_site__data',
reader: {
type: 'json',
root: 'rows'
},
listeners: {
exception: function (proxy, response) {
Max.reportException(response);
}
}
});
me.filters.createFilters();
me.store.load();
},
In the source, you can see a comment related to this.
// Call getMenu() to ensure the menu is created, and so, also are the filters. We cannot call
// createFilters() withouth having a menu because it will cause in a recursion to applyState()
// that ends up to clear all the filter values. This is likely to happen when we reorder a column
// and then add a new filter before the menu is recreated.
me.view.headerCt.getMenu();
You can test whether the menu has been created before applying your filter. If it hasn't, do it yourself.
if(!grid.getView().headerCt.menu){
grid.getView().headerCt.getMenu();
}

ExtJS 4 - Refreshing Summary Feature of Grid Panel Without Refreshing Entire View

I'm using ExtJS's GridPanel library to render a list of rows that have a CheckboxModel for selections. There is also a summary row that adds up all of the selected data and displays it in a row at the bottom of the GridPanel. The code for this is:
var sm = Ext.create('Ext.selection.CheckboxModel', {
/////////
// With large number of rows ... this takes forever
/////////
grid.getView().refresh();
/////////
/////////
listeners:{
selectionchange: function(selectionModel, selectedRecords, options){
// Do stuff
}
}
});
var selSumFn = function(column, selModel){
return function(){
var records = selModel.getSelection(),
result = 0;
//console.log("records:" + records.length);
Ext.each(records, function(record){
result += record.get(column) * 1;
});
return result;
};
};
var grid = Ext.create('Ext.grid.Panel', {
autoScroll:true,
features: [{
ftype: 'summary'
}],
store: store,
defaults: {
sortable:true
},
selModel: sm,
columns: [
{header: 'Column 1', width: 100, dataIndex: 'col1', summaryType: selSumFn('col1', sm)},
{header: 'Column 2', width: 100, dataIndex: 'col2', summaryType: selSumFn('col2', sm)}
],
width: 730,
height: 400 ,
title: 'Data',
renderTo: 'data-div',
viewConfig: {
stripeRows: true
},
listeners: {'beforerender' : {fn:function(){this.store.load();}}}
});
Is there any way to only refresh the summaryrow feature and not the entire view? Refreshing the view was the only way I could find to refresh the summary row when updates were made to checkbox selections of the GridPanel.
There is no support for this in Ext 4.0.2a. The grid view builds a single view template with features adding or modifying this template via a multitude of defined hooks. The result is a single template instance that cannot be easily dissected.
The best solution I found is to rebuild the template fragment that renders the summary row mimicking what the grid view is doing during the template construction process. Then overwrite the existing DOM for the summary row with a freshly rendered version.
I have created a patch (as an override) that adds a refresh() method to the Summary feature.
The code turned out to be surprisingly slick.
Ext.require('Ext.grid.feature.Summary', function() {
Ext.override(Ext.grid.feature.Summary, {
refresh: function() {
if(this.view.rendered) {
var tpl = Ext.create(
'Ext.XTemplate',
'{[this.printSummaryRow()]}',
this.getFragmentTpl()
);
tpl.overwrite(this.getRowEl(), {});
}
},
getRowEl: function() {
return this.view.el.down('tr.x-grid-row-summary');
}
});
});
In your selectionchange listener:
selectionchange: function(selectionModel, selectedRecords, options) {
grid.getView().getFeature(0).refresh();
}
See this JsFiddle for a live demo.
Of course this might break in future versions of Ext. However, it could turn out to be quite robust since it delegates most of its work to existing methods.
If you are using GroupingSummary, you need to use this instead:
refresh:function(){
var rowEls = this.view.el.query('tr.x-grid-row-summary');
var i = 1;
Ext.Array.each(this.summaryGroups, function(group){
var tpl = new Ext.XTemplate(
this.printSummaryRow(i),
this.getFragmentTpl()
);
tpl.overwrite(rowEls[i-1], {})
i++;
},this);

Resources