Como faço para obter uma caixa combinada ExtJS para agir como uma caixa de seleção HTML normal?
Pergunta
O EXTJS fornece uma caixa de combinação sofisticada que possui muitos recursos-digite a frente, permitindo a entrada de texto aleatória, ocultando todas as entradas na lista suspensa que não estrela o texto que já foi inserido.
Eu não quero esses recursos. Eu quero uma caixa selecionada que se comporta exatamente como se esperaria que uma caixa de seleção normal faria no baunilha HTML.
Eu quero que seja amarrado a um armazenamento de dados e quero todos os outros presentes de configuração do EXTJS que acompanham a caixa de combinação. Só não quero que os usuários/testadores estejam enlouquecendo quando encontram uma caixa selecionada que quebre o paradigma mental existente de como essas coisas funcionam.
Então, como posso obter uma caixa combinada ExtJS para agir mais como uma caixa selecionada? Ou estou usando o widget errado?
Solução
Você pode obter esse comportamento apenas usando a configuração adequada ao instanciar o objeto ext.form.comBobox:
var selectStyleComboboxConfig = {
fieldLabel: 'My Dropdown',
name: 'type',
allowBlank: false,
editable: false,
// This is the option required for "select"-style behaviour
triggerAction: 'all',
typeAhead: false,
mode: 'local',
width: 120,
listWidth: 120,
hiddenName: 'my_dropdown',
store: [
['val1', 'First Value'],
['val2', 'Second Value']
],
readOnly: true
};
var comboBox = new Ext.form.ComboBox(selectStyleComboboxConfig);
Substitua o mode: 'local'
e store
argumento no seu caso, se você quiser que ele esteja ligado a um Ext.data.JsonStore
por exemplo.
Outras dicas
A solução atualmente aceita funciona muito bem, mas se alguém quiser um ComboBox que também lida com a entrada do teclado como uma caixa de seleção HTML simples (por exemplo, cada vez que você pressiona "P" é seleciona o próximo item na lista que começa com "P"), o A seguir, pode ser útil:
{
xtype: 'combo',
fieldLabel: 'Price',
name: 'price',
hiddenName: 'my_dropdown',
autoSelect: false,
allowBlank: false,
editable: false,
triggerAction: 'all',
typeAhead: true,
width:120,
listWidth: 120,
enableKeyEvents: true,
mode: 'local',
store: [
['val1', 'Appaloosa'],
['val2', 'Arabian'],
['val3', 'Clydesdale'],
['val4', 'Paint'],
['val5', 'Palamino'],
['val6', 'Quarterhorse'],
],
listeners: {
keypress: function(comboBoxObj, keyEventObj) {
// Ext.Store names anonymous fields (like in array above) "field1", "field2", etc.
var valueFieldName = "field1";
var displayFieldName = "field2";
// Which drop-down item is already selected (if any)?
var selectedIndices = this.view.getSelectedIndexes();
var currentSelectedIndex = (selectedIndices.length > 0) ? selectedIndices[0] : null;
// Prepare the search criteria we'll use to query the data store
var typedChar = String.fromCharCode(keyEventObj.getCharCode());
var startIndex = (currentSelectedIndex == null) ? 0 : ++currentSelectedIndex;
var matchIndex = this.store.find(displayFieldName, typedChar, startIndex, false);
if( matchIndex >= 0 ) {
this.select(matchIndex);
} else if (matchIndex == -1 && startIndex > 0) {
// If nothing matched but we didn't start the search at the beginning of the list
// (because the user already had somethign selected), search again from beginning.
matchIndex = this.store.find(displayFieldName, typedChar, 0, false);
if( matchIndex >= 0 ) {
this.select(matchIndex);
}
}
if( matchIndex >= 0 ) {
var record = this.store.getAt(matchIndex);
this.setValue(record.get(valueFieldName));
}
}
}
}
Você tentou typeAhead = false
? Não tenho muita certeza se isso está próximo do que você deseja.
var combo = new Ext.form.ComboBox({
typeAhead: false,
...
});
var buf = [];
buf.push('<option>aA1</option>');
buf.push('<option>aA2</option>');
buf.push('<option>bA3</option>');
buf.push('<option>cA4</option>');
var items = buf.join('');
new Ext.Component({
renderTo: Ext.getBody(),
autoEl: {
tag:'select',
cls:'x-font-select',
html: items
}
});
Apenas use Ext.merge
função
Do documento: http://docs.sencha.com/extjs/4.2.1/#!/api/ext-method-merge