A combobox has a picker (a boundlist instance) which itself has a keynav (BoundListKeyNav).
How can I modify / customise this keynav instance?
Basically, by default it contains bindings for home / end. While this would be useful under normal circumstances, it is not when using a customised combobox. I want my home / end keys to function correctly, as they do before ext decides to hijack them (go to start / end of input contents).
Ideally, I want to do this in the configuration object of the combobx, like so:
{
xtype: 'combobox',
itemId: 'search',
emptyText: 'Search',
editable: true,
typeAhead: false,
hideTrigger: true,
queryMode: 'local',
minChars: 3,
displayField: 'name',
valueField: 'search'
}
It is made to behave in such a way that you can type anything in (to search) but can also choose auto completed searches.
The keynav lives at combo.listKeyNav, but the chunk of code which sets this up in ext fires no events to let us jump in and change it. It appears the combo has no configuration for such a thing either (seeing as the function setting listKeyNav doesn't take any config from our combo object).
FYI
It is the BoundListKeyNav which has these bindings hard coded. The combobox's onExpand creates the instance (taking no config anywhere, allowing for no customisation).
The only way is to override onExpand method of combo.
As Saki wrote customizing of the key navigation is only possible with overriding the onExpand method of the combobox - basically duplicating the original implementation (in case of ExtJS4).
For example:
onExpand: function() {
var me = this,
keyNav = me.listKeyNav,
selectOnTab = me.selectOnTab,
picker = me.getPicker();
// Handle BoundList navigation from the input field. Insert a tab listener specially to enable selectOnTab.
if (keyNav) {
keyNav.enable();
} else {
keyNav = me.listKeyNav = new Ext.view.BoundListKeyNav(me.inputEl, {
boundList: picker,
forceKeyDown: true,
tab: function(e) {
if (selectOnTab) {
this.selectHighlighted(e);
me.triggerBlur();
}
// Tab key event is allowed to propagate to field
return true;
},
enter: function(e) {
var selModel = picker.getSelectionModel(),
count = selModel.getCount();
this.selectHighlighted(e);
// Handle the case where the highlighted item is already selected
// In this case, the change event won't fire, so just collapse
if (!me.multiSelect && count === selModel.getCount()) {
me.collapse();
}
},
home: {
fn: Ext.emptyFn,
defaultEventAction: false
},
end: {
fn: Ext.emptyFn,
defaultEventAction: false
}
});
}
// While list is expanded, stop tab monitoring from Ext.form.field.Trigger so it doesn't short-circuit selectOnTab
if (selectOnTab) {
me.ignoreMonitorTab = true;
}
Ext.defer(keyNav.enable, 1, keyNav); //wait a bit so it doesn't react to the down arrow opening the picker
me.inputEl.focus();
}
Related
I'm using ag-grid (javascript) to display a large amount of rows (about 3,000 or more) and allow the user to enter values and it should auto-save them as the user goes along. My current strategy is after detecting that a user makes a change to save the data for that row.
The problem I'm running into is detecting and getting the correct values after the user enters a value. The onCellKeyPress event doesn't get fired for Backaspace or Paste. However if I attach events directly to DOM fields to catch key presses, I don't know how to know what data the value is associated with. Can I use getDisplayedRowAtIndex or such to be able to reliably do this reliably? What is a good way to implement this?
EDIT: Additional detail
My current approach is to capture onCellEditingStopped and then getting the data from the event using event.data[event.column.colId]. Since I only get this event when the user moves to a different cell and not just if they finish typing I also handle the onCellKeyPress and get the data from event.event.target (since there is no event.data when handling this event). Here is where I run into a hard-to-reproduce problem that event.event.target is sometimes undefined.
I also looked at using forEachLeafNode method but it returns an error saying it isn't supported when using infinite row model. If I don't use infinite mode the load time is slow.
It looks like you can bind to the onCellKeyDown event. This is sometimes undefined because on first keydown the edit of agGrid will switch from the cell content to the cell editor. You can wrap this around to check if there is a cell value or cell textContent.
function onCellKeyDown(e) {
console.log('onCellKeyDown', e);
if(e.event.target.value) console.log(e.event.target.value)
else console.log(e.event.target.textContent)
}
See https://plnkr.co/edit/XhpVlMl7Jrr7QT4ftTAi?p=preview
As been pointed out in comments, onCellValueChanged might work, however
After a cell has been changed with default editing (i.e. not your own custom cell renderer), the cellValueChanged event is fired.
var gridOptions = {
rowData: null,
columnDefs: columnDefs,
defaultColDef: {
editable: true, // using default editor
width: 100
},
onCellEditingStarted: function(event) {
console.log('cellEditingStarted', event);
},
onCellEditingStopped: function(event) {
console.log('cellEditingStopped', event);
},
onCellValueChanged: function(event) {
console.log('cellValueChanged', event);
}
};
another option could be to craft your own editor and inject it into cells:
function MyCellEditor () {}
// gets called once before the renderer is used
MyCellEditor.prototype.init = function(params) {
this.eInput = document.createElement('input');
this.eInput.value = params.value;
console.log(params.charPress); // the string that started the edit, eg 'a' if letter a was pressed, or 'A' if shift + letter a
this.eInput.onkeypress = (e) => {console.log(e);} // check your keypress here
};
// gets called once when grid ready to insert the element
MyCellEditor.prototype.getGui = function() {
return this.eInput;
};
// focus and select can be done after the gui is attached
MyCellEditor.prototype.afterGuiAttached = function() {
this.eInput.focus();
this.eInput.select();
};
MyCellEditor.prototype.onKeyDown = (e) => console.log(e);
// returns the new value after editing
MyCellEditor.prototype.getValue = function() {
return this.eInput.value;
};
//// then, register it with your grid:
var gridOptions = {
rowData: null,
columnDefs: columnDefs,
components: {
myEditor: MyCellEditor,
},
defaultColDef: {
editable: true,
cellEditor: 'myEditor',
width: 100
},
onCellEditingStarted: function(event) {
console.log('cellEditingStarted', event);
},
onCellEditingStopped: function(event) {
console.log('cellEditingStopped', event);
}
};
Normally, when you select an item in a combobox, you would expect it to fire the select event. However, if you try to select an item that was already selected, the select event is not fired. That is the "normal" behavior of an ExtJs combobox.
I have a specific need for an ExtJS combobox: I need it to fire the select event even if I re-select the same value. But I cannot get it to work. Any help would be much appreciated!
Example here: https://fiddle.sencha.com/#view/editor&fiddle/2n11
Open the dev tools to see when the select event is fired.
I'm using ExtJS Classic 6.6.0.
Edit: I answered my own question and updated the Fiddle with working solution.
try to look at this:
ExtJS 4 Combobox event for selecting selected value
Its for earlier ExtJS version, but catching click event for itemlist may help you out too..
I found the culprit: it all happens in the SelectionModel of the combobox BoundList, in the method doSingleSelect.
So if we extend Ext.Selection.DataViewModel and Ext.form.field.ComboBox, we can force the select event to be fired every time.
Ext.define( "MyApp.selection.DataViewModelExt", {
"extend": "Ext.selection.DataViewModel",
"alias": "selection.dataviewmodelext",
"doSingleSelect": function(record, suppressEvent) {
var me = this,
changed = false,
selected = me.selected,
commit;
if (me.locked) {
return;
}
// already selected.
// should we also check beforeselect?
/*
if (me.isSelected(record)) {
return;
}
*/
commit = function() {
// Deselect previous selection.
if (selected.getCount()) {
me.suspendChanges();
var result = me.deselectDuringSelect([record], suppressEvent);
if (me.destroyed) {
return;
}
me.resumeChanges();
if (result[0]) {
// Means deselection failed, so abort
return false;
}
}
me.lastSelected = record;
if (!selected.getCount()) {
me.selectionStart = record;
}
selected.add(record);
changed = true;
};
me.onSelectChange(record, true, suppressEvent, commit);
if (changed && !me.destroyed) {
me.maybeFireSelectionChange(!suppressEvent);
}
}
});
We also must extend the combobox to force using our extended DataViewModel. The only thing to change is the onBindStore method where it instancies the DataViewModel:
Ext.define( "MyApp.form.field.ComboBoxEx", {
"extend": "Ext.form.field.ComboBox",
"alias": "widget.comboboxex",
"onBindStore": function(store, initial) {
var me = this,
picker = me.picker,
extraKeySpec,
valueCollectionConfig;
// We're being bound, not unbound...
if (store) {
// If store was created from a 2 dimensional array with generated field names 'field1' and 'field2'
if (store.autoCreated) {
me.queryMode = 'local';
me.valueField = me.displayField = 'field1';
if (!store.expanded) {
me.displayField = 'field2';
}
// displayTpl config will need regenerating with the autogenerated displayField name 'field1'
if (me.getDisplayTpl().auto) {
me.setDisplayTpl(null);
}
}
if (!Ext.isDefined(me.valueField)) {
me.valueField = me.displayField;
}
// Add a byValue index to the store so that we can efficiently look up records by the value field
// when setValue passes string value(s).
// The two indices (Ext.util.CollectionKeys) are configured unique: false, so that if duplicate keys
// are found, they are all returned by the get call.
// This is so that findByText and findByValue are able to return the *FIRST* matching value. By default,
// if unique is true, CollectionKey keeps the *last* matching value.
extraKeySpec = {
byValue: {
rootProperty: 'data',
unique: false
}
};
extraKeySpec.byValue.property = me.valueField;
store.setExtraKeys(extraKeySpec);
if (me.displayField === me.valueField) {
store.byText = store.byValue;
} else {
extraKeySpec.byText = {
rootProperty: 'data',
unique: false
};
extraKeySpec.byText.property = me.displayField;
store.setExtraKeys(extraKeySpec);
}
// We hold a collection of the values which have been selected, keyed by this field's valueField.
// This collection also functions as the selected items collection for the BoundList's selection model
valueCollectionConfig = {
rootProperty: 'data',
extraKeys: {
byInternalId: {
property: 'internalId'
},
byValue: {
property: me.valueField,
rootProperty: 'data'
}
},
// Whenever this collection is changed by anyone, whether by this field adding to it,
// or the BoundList operating, we must refresh our value.
listeners: {
beginupdate: me.onValueCollectionBeginUpdate,
endupdate: me.onValueCollectionEndUpdate,
scope: me
}
};
// This becomes our collection of selected records for the Field.
me.valueCollection = new Ext.util.Collection(valueCollectionConfig);
// This is the selection model we configure into the dropdown BoundList.
// We use the selected Collection as our value collection and the basis
// for rendering the tag list.
//me.pickerSelectionModel = new Ext.selection.DataViewModel({
me.pickerSelectionModel = new MyApp.selection.DataViewModelExt({
mode: me.multiSelect ? 'SIMPLE' : 'SINGLE',
// There are situations when a row is selected on mousedown but then the mouse is dragged to another row
// and released. In these situations, the event target for the click event won't be the row where the mouse
// was released but the boundview. The view will then determine that it should fire a container click, and
// the DataViewModel will then deselect all prior selections. Setting `deselectOnContainerClick` here will
// prevent the model from deselecting.
ordered: true,
deselectOnContainerClick: false,
enableInitialSelection: false,
pruneRemoved: false,
selected: me.valueCollection,
store: store,
listeners: {
scope: me,
lastselectedchanged: me.updateBindSelection
}
});
if (!initial) {
me.resetToDefault();
}
if (picker) {
me.pickerSelectionModel.on({
scope: me,
beforeselect: me.onBeforeSelect,
beforedeselect: me.onBeforeDeselect
});
picker.setSelectionModel(me.pickerSelectionModel);
if (picker.getStore() !== store) {
picker.bindStore(store);
}
}
}
}
});
Then just use the extended combobox in your app. By doing that, the select event will be fired every time.
I have a site with a table build with Dojo/DGrid.
Some columns of the grid use editor: dijit/form/FilteringSelect as editor, which works perfect. As the user hits the return key, the value is accepted and the editor closes.
Other columns of the same grid have a custom defined renderCell, because the unterdying store url differs in every row:
function myCustomRenderCell(object, item, node) {
node.innerHTML = '<div class="myClass"></div>';
var filteringSelect = new FilteringSelect({
label: 'myLabel',
name: 'myName',
displayedValue: item.myValue,
store: new DstoreAdapter (
new RestMemoryStore ({
idProperty: 'id',
target: 'myUrlToJsonData',
})
),
onChange: function(newValue) {
var rowData = filteringSelect.store.get(newValue);
var gridCell = this.domNode.offsetParent;
var dataCell = grid.cell(gridCell);
rowData.then(function(row){
var eventObject = {
grid: this,
cell: dataCell,
oldValue: "",
value: row.name,
bubbles: true,
cancelable: true
};
on.emit(dataCell.element, 'dgrid-datachange', eventObject);
grid.updateDirty(dataCell.row.id, 'myLabel', row.name);
});
}
}, node.children[0]);
filteringSelect._destroyOnRemove = true;
filteringSelect.startup();
}
Unlike the default FilteringSelect mentions in the beginning this one is not left as the use hits the return key. The value is processed correctly. But except of pressing tab which places the cursor inside the next custom editor or using the mouse there is no way to leave this editor.
Any ideas how to set up this custom build FilteringSelect to dismiss on return like the default editor in the grid does?
try out: add an event handler for key press:
onKeyPress: function(event){
if (event.charOrCode == keys.ENTER) {
filteringSelect.set("focused", false);
}
}
Thanks to Manjunatha for the helpful hint.
I have a form with fields and a grid.
{ textfield },
{ textfield },
{ textfield },
etc...,
{ grid with toolbar: filefield }
On the grid, I have added a filefield toolbar which I have added a change listener to add the file to the grid:
addAttachment: function (field, value, eOpts) {
var me = this,
grid = field.up('grid'),
gridStore = grid.getStore();
gridStore.add(
{
filename: value,
dateadded: new Date()
});
}
Basically, I want to add the attachments to the grid first so that I can send multiple files to the server. Is this possible?
Currently, doing form.getValues() only gets the other fields inside the form but not the toolbar. Getting the store items also doesn't seem to include the correct file paths as they are prefixed with c:\fakepath\.
What I want is to only push all form values including all the files which are stored in the grid on the Save event. Any luck guys?
Ok. Since, no one answered, here's what I've done:
First, instead of using a filefield in the tbar of the grid, I use a button instead. I've added a click listener to that button which adds a hidden filefield to the form:
addAttachment: function (button) {
var me = this,
form = button.up('form'),
grid = button.up('grid'),
gridStore = grid.getStore(),
newFileField = {
xtype: 'filefield',
hidden: true,
unused: true, //custom property to check if there is already an unused field
listeners: {
change: function (field, value, eOpts) {
gridStore.add(
{
filename: value,
dateadded: new Date()
});
field.unused = false;
}
}
};
//if there is already an unused field, we don't need to add a newField to the form
if (!form.down('filefield[unused=true]')) {
form.add(newFileField);
}
//imitate the filefield trigger. this will show the file dialog
form.down('filefield[unused=true]').fileInputEl.dom.click();
}
So that's it. Basically, the button just imitates the filefield file dialog trigger but what actually happens is it adds a new filefield to the form. So calling form.getForm().submit() now includes all files which are also in the grid.
I hope this should help anyone in the future.
CHEERS!
I'm trying to implement a select that calls a function even if the same option is selected twice. Following one of the answers on this thread, I've set the selectedIndex to -1 on focus. However, I'm still not getting the function call when the same option is selected twice.
var scaleSelect = new ComboBox({
id: "scale_select",
style: {width: "150px"},
name: "scale_select",
placeHolder: "Choisir une échelle",
store: scaleStore,
disabled: true,
onFocus: function() {
this.selectedIndex = -1;
console.log(this.selectedIndex); //-1
},
onChange: function(value){
mapScale = value;
window.myMap.setScale(mapScale);
}
}, "scale_select");
scaleSelect.startup();
UPDATE Attempting to set the selected index within onChange still doesn't call the function--wondering if this has to do with the fact that selected index is undefined onChange..
var scaleSelect = new ComboBox({
id: "scale_select",
style: {width: "150px"},
name: "scale_select",
placeHolder: "Choisir une échelle",
store: scaleStore,
disabled: true,
onChange: function(value){
mapScale = value;
window.myMap.setScale(mapScale);
var mySelect = document.getElementById("scale_select");
console.log(this.selectedIndex) //undefined
this.selectedIndex = -1;
mySelect.selectedIndex = -1;
console.log(this.selectedIndex); //-1
console.log(mySelect.selectedIndex); //-1
}
}, "scale_select");
scaleSelect.startup();
I tested every things that i knew with no success. I wondering about the thread that you linked and answers with upvotes! I the reason is that a selected option is not an option any more. But i have a suggestion:
Create your own custom Select
It is only a textbox and a div under that with some links line by line.
So I think the problem is that after you've picked a value in the select, it doesn't lose focus. So your onFocus handler won't get called unless the user actually clicks somewhere else on the page. If she doesn't do that, then the select's value won't fire the onChange if she selects the same value again.
So instead of setting the selected index on focus, why not do it in onChange, after you've handled the change? That way your select will be primed for another selection as soon as you're done treating the current one.
UPDATE
Ok, so looking at the Dojo code, this is the best I could come up with:
var scaleSelect = new ComboBox({
id: "scale_select",
style: {width: "150px"},
name: "scale_select",
placeHolder: "Choisir une échelle",
store: scaleStore,
disabled: true,
onChange: function(value){
if(value) { // the .reset() call below will fire the onChange handler again, but this time with a null value
mapScale = value;
window.myMap.setScale(mapScale);
console.log("Changed to", value, this);
this.reset(); // This is the magic here: reset so you are guaranteed to isseu an "onChange" the next time the user picks something
}
}
}, "scale_select");
scaleSelect.startup();
Note that you need to start the whole thing with no value - or else that initial value won't issue an "onChange" event, and every time you reset the widget, it'll go back to the initial value...
Hope this helps!