ExtJS 4: Excel-style keyboard navigation in an editable Grid - extjs

Using ExtJS 4 I would like to create a grid into which the user will enter a long list of numbers. I would like the user to be able to finish editing one cell by pressing "Enter" and then automatically move to the cell below and start editing.
Ext.grid.plugin.CellEditing seems to work well for the purpose of editing, but I can't find a way to detect and handle the keyUp event.
I tried approaching the matter using the "edit" event with this code:
selType: 'cellmodel',
plugins: [
Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit: 1,
listeners: {
edit: function (editor, e, eOpts) {
// If the event is fired by pressing "Enter", the column and row associated with event will
// be the same as the currently selected row and column
if (e.grid.selModel.position.column == e.colIdx && e.grid.selModel.position.row == e.rowIdx){
// Check if we are in the final row
if (e.rowIdx+1 == e.grid.getStore().getTotalCount()){
return true;
}
editor.startEditByPosition({row: e.rowIdx+1, column: e.colIdx});
return false;
}
}
}
})
],
The problem with this approach is that if the user starts editing the cell, then clicks on a GUI element outside of the Grid, the edit event does not distinguish this from the "Enter" key being pressed. Can this be fixed?
Perhaps I should be trying to implement a custom SelectionModel instead? How does one go about starting with that approach?

something like this ???
when editing try using tab, shift + tab, enter, and shift + enter
what i did is override the cellediting and selection.rowmodel
actually, i have had a similar question with you. and #Lionel Chan help me solve it.
and my solution above is base on his idea.
Note : only work with Extjs 4.0.7
EDIT (if my jsfiddle broken, here's the override)
Ext.override(Ext.grid.plugin.CellEditing,{
onSpecialKey: function(ed, field, e) {
var grid = this.grid,sm;
if (e.getKey() === e.TAB) {
e.stopEvent();
sm = grid.getSelectionModel();
if (sm.onEditorTab)sm.onEditorTab(this, e);
}else if(e.getKey() === e.ENTER){
e.stopEvent();
sm = grid.getSelectionModel();
if (sm.onEditorEnter)sm.onEditorEnter(this, e);
}
}
});
Ext.override(Ext.selection.RowModel, {
lastId:null,
onEditorTab: function(ep, e) {
var me = this,
view = me.view,
record = ep.getActiveRecord(),
header = ep.getActiveColumn(),
position = view.getPosition(record, header),
direction = e.shiftKey ? 'left' : 'right',
newPosition = view.walkCells(position, direction, e, false),
newId=newPosition.row,
grid=view.up('gridpanel');
if (me.lastId!=newId && me.lastId!=null){
deltaX = me.lastId<newId? -Infinity : Infinity;
header=grid.headerCt.getHeaderAtIndex(newPosition.column);
if(header){
while(!header.getEditor()){
newPosition= view.walkCells(newPosition,direction, e, false);
header=grid.headerCt.getHeaderAtIndex(newPosition.column);
}
}
}else{
deltaX = ep.context.column.width * (direction== 'right' ? 1 : -1);
}
grid.scrollByDeltaX(deltaX);
me.lastId=newPosition.row;
Ext.defer(function(){
if (newPosition)ep.startEditByPosition(newPosition);
else ep.completeEdit();
}, 100);
},
onEditorEnter:function(ep,e){
var me = this,
view = me.view,
record = ep.getActiveRecord(),
header = ep.getActiveColumn(),
position = view.getPosition(record, header),
direction = e.shiftKey ? 'up' : 'down',
newPosition = view.walkCells(position, direction, e, false),
newId=newPosition.row,
grid=view.up('gridpanel');
deltaY=20 * (direction== 'down' ? 1 : -1);
grid.scrollByDeltaY(deltaY);
me.lastId=newPosition.row;
Ext.defer(function(){
if (newPosition)ep.startEditByPosition(newPosition);
else ep.completeEdit();
}, 100);
}
});

Starting with the suggestion of "Warung Nasi 49",
I Wrote this override:
Ext.define('Override.Ext.grid.plugin.CellEditing',
{
override: 'Ext.grid.plugin.CellEditing',
onSpecialKey: function (ed, field, e) {
var grid = this.grid,
nbCols = grid.columns.length - 1, //start from 0
nbRows = grid.getStore().getTotalCount() - 1, //start from 0
currentCol = this.context.colIdx,
currentRow = this.context.rowIdx;
//forward
if (!e.shiftKey && (e.getKey() === e.ENTER || e.getKey() === e.TAB)) {
e.stopEvent();
//Detect next editable cell
do {
if (this.startEdit(currentRow, currentCol + 1))
break;
else {
currentCol++;
if (currentCol >= nbCols) {
currentRow++;
currentCol = -1;
}
}
} while (currentRow <= nbRows);
}
//backward
if (e.shiftKey && (e.getKey() === e.ENTER || e.getKey() === e.TAB)) {
e.stopEvent();
//Detect previous editable cell
do {
if (this.startEdit(currentRow, currentCol - 1))
break;
else {
currentCol--;
if (currentCol < 0) {
currentRow--;
currentCol = nbCols+1;
}
}
} while (currentRow >=0);
}
}
},
null);
This override allow both TAB and ENTER navigation (forward/backward via SHIFT).
When the last cell of row is reached, the firt editable cell of the next row is focused.

Related

ExtJS4- Year and month date picker - disable all future dates

I am using a Ext.picker.Month.
Setting maxDate does not disable dates which are grater than the maxDate value, but causes a validation error when selecting one.
How can I disable all future dates?
See fiddle -
1. Set maxDate to new Date()
2. Use ExtJS 4.2
You are instantiating a MonthPicker, not a DatePicker, yet you are using dozens of config options that are only available for a DatePicker.
You can see here how to instantiate a MonthPicker. As you can see there and especially in the docs, MonthPicker does not provide a config option to disable anything. Also, if you check the DatePicker behaviour, you see that disabledDates option does not change anything in MonthPicker, only AFTER the month has been selected, all days in the DatePicker are disabled.
So you would be on your own in implementing disabledDates for the MonthPicker, which I would do by looking at the code from DatePicker and MonthPicker, and trying to transfer.
Try this one...working on ExtJS 6.0.0.
You need to override 'Ext.picker.Month'
find attached image
Accepted values -
new RegExp('(?:)'); disable all month/year
new RegExp('^((?!^Apr/2016$|^May/2016$|^Jun/2016$|^Jul/2016$).)*$') disable all values other than Apr/May/Jun/Jul 2016
CSS -
.x-monthpicker-disabled {
background-color: #eee !important;
cursor: default !important;
color: #bbb !important;
}
disabledCls: Ext.baseCSSPrefix + 'monthpicker-disabled',
disabledMonthYearsRE: null,
disabledMonthYearsText: 'Disabled',
updateBody: function () {
//default Extjs code
if (me.rendered) {
//default Extjs code
//remove disabled cls and tooltip
years.removeCls(disabledCls);
months.set({
'data-qtip': ''
});
years.set({
'data-qtip': ''
});
months.removeCls(disabledCls);
//default Extjs code
if (dmyMatch) {
if (month == null && year == null) {
months.set({
'data-qtip': dmyText
});
months.addCls(disabledCls);
}
yrInView = false;
for (y = 0; y < yLen; y++) {
yr = yearNumbers[y];
el = Ext.fly(yearItems[y]);
if (dmyMatch.toString().indexOf(yr) == -1) {
el.dom.setAttribute('data-qtip', dmyText);
el.addCls(disabledCls);
}
if (yr == year) {
yrInView = true;
}
}
if (year != null && yrInView) {
for (m = 0; m < mLen; m++) {
mNo = m;
if (mNo < monthOffset) {
mNo = mNo * 2;
} else {
mNo = (mNo - monthOffset) * 2 + 1;
}
mt = months.elements[mNo];
if (dmyMatch.test(mt.text + "/" + year)) {
mt.setAttribute('data-qtip', dmyText);
mt.className = disabledCls + ' ' + mt.className;
}
}
} else {
//Add tooltip 'disabled'
months.set({
'data-qtip': dmyText
});
months.addCls(disabledCls);
}
}
}
},
//Disable month and year click for disabled values
onMonthClick: function (target, isDouble) {
var me = this;
if (!me.disabled && !Ext.fly(target).hasCls(me.disabledCls)) {
//default Extjs code
}
},
onYearClick: function (target, isDouble) {
var me = this;
if (!me.disabled && !Ext.fly(target).hasCls(me.disabledCls)) {
//default Extjs code
}
}

How to get actioncolumn icon component?

I'm searching two days and can't find how to get access to actioncolumn component (NOT html) on rowselect. I need to set event on icon click using Saki's component communication technique (source).
My column looks like:
I found a way how to show/hide buttons on change row selection (this code uses in GridPanel):
sm: new Ext.grid.RowSelectionModel({
singleSelect: true,
listeners: {
beforerowselect: function(grid, rowIndex, record) {
// 7 is the last cell index
var cell = grid.grid.getView().getCell( rowIndex, 7 );
//select icons in cell
var icons = Ext.DomQuery.select('.x-action-col-icon', cell);
//for each DOM element
Ext.each(icons, function(icon, index) {
currentIcon = Ext.get(icon);
//if not 1st button
if (index !== 0) {
//Delete class that hides. Class 'x-hidden' also works
currentIcon.removeClass('x-hide-display'); //show icon
}
});
},
rowdeselect: function(grid, rowIndex, record) {
// 7 is the last cell index
var cell = grid.grid.getView().getCell( rowIndex, 7 );
//select icons in cell
var icons = Ext.DomQuery.select('.x-action-col-icon', cell);
//for each DOM element
Ext.each(icons, function(icon, index) {
currentIcon = Ext.get(icon);
//if not 1st button
if (index !== 0) {
//Delete class that hides. Class 'x-hidden' also works
currentIcon.addClass('x-hide-display'); //show icon
}
});
}
}
});
Ok. Next. I want to show another window on click (set click event). But I don't know how to get access from Window/Viewport:
//get items
this.loanGrid = this.items.itemAt(0);
this.documentsGridWindow = this.items.itemAt(2);
//add events
this.loanGrid.on ({
scope: this,
afterrender: function() {
selModel = this.loanGrid.getSelectionModel();
selModel.on({
scope: this,
rowselect: function (grid, rowIndex, keepExisting, record) {
//HOW TO GET actioncolumn 2nd button here???
}
});
}
});
I also tried to set id to this icon on beforerowselect, but on rowselect this code Ext.getCmp('icon-id') returns undefined.
up() and down() functions not helps me too =(
HELP please! =)
p.s. Sad, but Ext.ComponentQuery works only from ExtJS 4.
So finally I re-wrote some parts of my application.
First we need to add some options to actioncolumn:
dataIndex: 'action',
id: 'action',
Grid row buttons show/hide now is independent of actioncolumn move:
/**
* buildSelectionModel
*/
buildSelectionModel: function() {
var sm = new Ext.grid.RowSelectionModel({
singleSelect: true,
listeners: {
scope: this,
rowselect: function(grid, rowIndex, record) {
this.toggleFirstButtonShowState(grid.grid, rowIndex);
},
rowdeselect: function(grid, rowIndex, record) {
this.toggleFirstButtonShowState(grid.grid, rowIndex);
}
}
});
return sm;
},
/**
* toggleFirstButtonShowState
*/
toggleFirstButtonShowState: function(grid, rowIndex) {
//'action' is data index of
var colIndex = this.getColumnIndexByDataIndex(grid, 'action');
console.log(colIndex);
// 7 is the last cell index
var cell = grid.getView().getCell( rowIndex, colIndex);
//select icons in cell
var icons = Ext.DomQuery.select('.x-action-col-icon', cell);
//for each DOM element
Ext.each(icons, function(icon, index) {
currentIcon = Ext.get(icon);
//if not 1st button
if (index !== 0) {
//Show/delete class that hides. Class 'x-hidden' also works
currentIcon.toggleClass('x-hide-display'); //show/hide icon
}
});
},
getColumnIndexByDataIndex: function(grid, dataIndex) {
//columns
gridColumns = grid.getColumnModel().columns;
for (var i = 0; i < gridColumns.length; i++) {
if (gridColumns[i].dataIndex == dataIndex) {
return i;
}
}
Viewport part:
//get selection model
selModel = this.loanGrid.getSelectionModel();
selModel.on({
scope: this,
rowselect: function (grid, rowIndex, keepExisting, record) {
//get second icon in actioncolumn
var icon = grid.grid.getColumnModel().getColumnById('action').items[1];
//save context
var self = this;
//add handler by direct set
icon.handler = function(grid, rowIndex, colIndex) {
//open documents window
self.documentsGridWindow.show();
};
}
});
All works as expected!

ng-grid - Keep overall width the same when altering column widths

I have an ng-grid with 6 columns in it, and as a default set up each column is 100px, so the grid itself is 600px. The columns are resizable but I want to keep the overall grid width the same, to ensure that there are no horizontal scroll bars. So, for example, if I change the second columns width to 150px I would want the overall width to stay at 600px (so maybe an adjacent cell will change size to 50px) - this way I don't get a scroll bar.
Does anybody know if there is a plugin that can do this/help me accomplish this?
I've included a plunker: http://plnkr.co/edit/4LRHQPg7w2eDMBafvy6b?p=preview
In this example, I would want to keep the table width at 600px, so if I expand "Field 2" you will see "Field 4" go off the edge of the viewable area for the grid and a horizontal scroll bar appear. The behaviour I want is for a different column (probably the adjacent column - "Field 3") to shrink in size automatically, so that the grid stays at 600px and the horizontal scroll bar doesn't appear.
After a lot of time searching the web for an answer, I started with Paul Witherspoon idea of watching the isColumnResizing property and after reading about ng-grid plugins I came up with this plugin solution:
Plunker: http://plnkr.co/edit/Aoyt73oYydIB3JmnYi9O?p=preview
Plugin code:
function anchorLastColumn () {
var self = this;
self.grid = null;
self.scope = null;
self.services = null;
self.init = function (scope, grid, services) {
self.grid = grid;
self.scope = scope;
self.services = services;
self.scope.$watch('isColumnResizing', function (newValue, oldValue) {
if (newValue === false && oldValue === true) { //on stop resizing
var gridWidth = self.grid.rootDim.outerWidth;
var viewportH = self.scope.viewportDimHeight();
var maxHeight = self.grid.maxCanvasHt;
if(maxHeight > viewportH) { // remove vertical scrollbar width
gridWidth -= self.services.DomUtilityService.ScrollW;
}
var cols = self.scope.columns;
var col = null, i = cols.length;
while(col == null && i-- > 0) {
if(cols[i].visible) {
col = cols[i]; // last column VISIBLE
}
}
var sum = 0;
for(var i = 0; i < cols.length - 1; i++) {
if(cols[i].visible) {
sum += cols[i].width;
}
}
if(sum + col.minWidth <= gridWidth) {
col.width = gridWidth - sum; // the last gets the remaining
}
}
});
}
}
and in the controller
$scope.gridOptions = {
data: 'myData',
enableColumnResize: true,
plugins: [new anchorLastColumn()],
columnDefs: $scope.columnDefs
};
It is not a perfect solution but works for me and I hope that it will help others.
I found a way to do this using a watch on the isColumnResizing property:
$scope.$watch('gridOptions.$gridScope.isColumnResizing', function (newValue, oldValue) {
if (newValue === false && oldValue === true) { //on stop resizing
$scope.ColResizeHandler($scope.gridOptions.$gridScope.columns);
}
}, true);
then I was able to resize the columns in the resize handler I created:
$scope.ColResizeHandler = function (columns) {
var origWidth;
var col1 = undefined;
var col2 = undefined;
var widthcol2;
var found = false;
var widthDiff = 0;
angular.forEach(columns, function (value) {
if (col2 == undefined && value.visible) {
if (found) {
origWidth += value.width;
col2 = value;
colSizeLimits(col2, widthDiff);
found = false;
}
if (value.origWidth != undefined && value.origWidth != value.width && col2 == undefined) {
found = true;
col1 = value;
widthDiff = value.width - value.origWidth;
origWidth = value.origWidth;
}
}
});
if (col2 == undefined) {
//this was the last visible column - don't allow resizing
col1.width = origWidth;
}
else {
//ensure limits haven't been blown to cope with reizing
if (col1.width + col2.width != origWidth) {
var diff = (col1.width + col2.width) - origWidth;
colSizeLimits(col1, diff);
}
}
col1.origWidth = col1.width;
col2.origWidth = col2.width;
}
There are 2 issues with this.
1 - if you resize and drag the column sizer outside of the grid (i.e. all the way over and out of the ng-grid viewable area) the isColumnResizing watch doesn't execute when you stop dragging and release the resizer. (I think this may be a bug in ng-grid because it does actually resize the column to where you have dragged the resizer, even if it is outside the grids viewable area, it just doesn't fire the watch code).
2 - if you avoid this issue and just drag within the viewable grid area then the columns will resize but only after you finish dragging the resizer, so the ui looks a little funny (i.e. if I expand a column then the adjacent column will not shrink until I click off the resizer and stop dragging).
I'll be working on these issues and will post any updates/fixes I find.

EXTJS 4 - How to skip individual cells when using tab key through a grid but keep tab press start edit next editable cell?

I have a grid, with cell editing and row selection model. I use tab to go to next cell and start to edit it, but there are cells which I need to skip editing, but when peressing a tab need to go to next editable cell.
If I just "return false" from "beforeedit" event, it cancels the whole editing process so I need to use the mouse again, thats wrong.
How can I skipp cells but keep the tabbing working?
plugins: [
Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit: 1,
listeners: {
beforeedit: {
fn: me.onCellEditingBeforeEdit,
scope: me
}
}
})
]
here is the before edit function:
onCellEditingBeforeEdit: function(editor, e, eOpts) {
var isEditable=this.isCellEditabe(editor, e); // return false if the cell is not editable
if (!isEditable)
{
return false;
}
}
I found somewhere in a .net forum the solution:
Ext.selection.RowModel.override({
onEditorTab: function(editingPlugin, e) {
var me = this,
view = me.views[0],
record = editingPlugin.getActiveRecord(),
header = editingPlugin.getActiveColumn(),
position = view.getPosition(record, header),
direction = e.shiftKey ? 'left' : 'right',
columnHeader;
// We want to continue looping while:
// 1) We have a valid position
// 2) There is no editor at that position
// 3) There is an editor, but editing has been cancelled (veto event)
do {
position = view.walkCells(position, direction, e, me.preventWrap);
columnHeader = view.headerCt.items.getAt(position.column);
} while (position && (!columnHeader.getEditor(record) || !editingPlugin.startEditByPosition(position)));
}
});
use this as config in your current grid:
var grid = Ext.create('Ext.grid.Panel', {
...
selModel: Ext.create('selection.cellmodel', {
onEditorTab: function(editingPlugin, e) {
var me = this,
direction = e.shiftKey ? 'left' : 'right',
position = me.move(direction, e);
if (position) {
while(!editingPlugin.startEdit(position.row, position.column)){
position = me.move(direction, e);
// go to first editable cell
if(!position) editingPlugin.startEdit(0, 1); // TODO: make this dynamic
}
me.wasEditing = false;
} else {
// go to first editable cell
if (editingPlugin.startEdit(0, 1)) { // TODO: make this dynamic
me.wasEditing = false;
}
}
},
}),
//selType: 'cellmodel', // remove selType
...
})

Highlight a part of an extjs4 line chart

In the extjs 4.1.1a code below is a working example of a line chart. Now I need to highlight a part of that chart on a given min and max timestamp.
{'xtype' : 'chart',
'store' : 'ChartData',
'height' : '100%',
'width' : '100%',
'legend' : {'position' : top},
'axes': [{
'title': 'Power',
'type': 'Numeric',
'position': 'left',
'fields': ['power']
},{
'title': 'Timestamp',
'type': 'Numeric',
'position': 'bottom',
'fields': ['timestamp'],
'minorTickSteps': 3
}],
'series': [{
'type': 'line',
'fill': true,
'axis' : 'left',
'xField': 'timestamp',
'yField': 'power'
}]}
I've searched the sencha forum and found nothing in particular that meets my requirements.
For now I managed to change the color of the points on the line chart with a custom renderer.
'renderer': function(sprite, record, attr, index, store) {
var item = store.getAt(index);
if(item != undefined && (item.get('timestamp') < startdate || item.get('timestamp') > enddate)){
return Ext.apply(attr, {'fill': '#00cc00', 'stroke-width': 3, 'radius': 4});
}else{
return Ext.apply(attr, {'fill': '#ff0000', 'stroke-width': 3, 'radius': 4});
}}
But I have not found a way to change the color below the line.
Any suggestions on that?
UPDATE - Working fine now
I implement a solution based on the answer given by Colombo.
doCustomDrawing: function () {: function (p){
var me = this, chart = me.chart;
if(chart.rendered){
var series = chart.series.items[0];
if (me.groupChain != null) {
me.groupChain.destroy();
me.groupChain = null;
}
me.groupChain = Ext.create('Ext.draw.CompositeSprite', {
surface: chart.surface
});
if(series != null && series.items != null){
var surface = chart.surface;
var pathV = 'M';
var first = true;
// need first and last x cooridnate
var mX = 0,hX = 0;
Ext.each(series.items, function(item){
var storeItem = item.storeItem,
pointX = item.point[0],
pointY = item.point[1];
// based on given startdate and enddate start collection path coordinates
if(!(storeItem.get('timestamp') < startdate || storeItem.get('timestamp') > enddate)){
if(hX<pointX){
hX = pointX;
}
if(first){
first = false;
mX = pointX;
pathV+= + pointX + ' ' + pointY;
}else{
pathV+= ' L' + pointX + ' ' + pointY;
}
}
});
var sprite = Ext.create('Ext.draw.Sprite', {
type: 'path',
fill: '#f00',
surface: surface,
// to draw a sprite with the area below the line we need the y coordinate of the x axe which is in my case items[1]
path : pathV + ' L'+ hX + ' ' + chart.axes.items[1].y + ' L'+ mX + ' ' + chart.axes.items[1].y + 'z'
});
me.groupChain.add(sprite);
me.groupChain.show(true);
}
}}
This looks really good and has the effect I was hoping for and in case you resize the container the new sprite is cleared from the chart. Thx to Colombo again.
This is possible to implement. Here is how I would do it.
1. Add a listener for afterrender event for series.
listeners: {
afterrender: function (p) {
this.doCustomDrawing();
},
scope: me
}
2. Create a CompositeSprite
doCustomDrawing: function () {
var me = this, chart = me.chart;
if (chart.rendered) {
var series = chart.series.items[0];
if (me.groupChain != null) {
me.groupChain.destroy();
me.groupChain = null;
}
me.groupChain = Ext.create('Ext.draw.CompositeSprite', {
surface: chart.surface
});
// Draw hilight here
Ext.each(series.items, function (item) {
var storeItem = item.storeItem,
pointX = item.point[0],
pointY = item.point[1];
//TODO: Create your new line sprite using pointX and pointY
// and add it to CompositeSprite me.groupChain
});
me.groupChain.show(true);
}
},
There is no "built-in" way to go about this. You are probably running into some difficulties looking for it because "highlighting" a line chart currently means something totally different in the ExtJS API. It normally refers to making the line and markers bold when you hover the mouse over a data series.
However your idea sounds interesting, I might need use this in a project I have coming up.
I don't have the time to work out the exact code right now but this could be done by creating a rectangular sprite and adding it to the chart's surface property.
You can do that even after the chart has been all rendered using the Ext.draw.Surface.add method as described here in the docs.
You will have to come up with logic for determining width and positioning, if I remember the chart API properly, you should be able to extract x coordinates (horizontal location) of individual records by fishing around in the items property of the Ext.chart.series.Line object inside the chart.
The height of the highlight should be easy though - just read the height of the chart.

Resources