Issue with configuring ExtJS combo box

While using combos in an input form, I encountered an intriguing issue. The form has combos that retrieve data from JSON stores. Everything works smoothly when adding a new record, but when editing an existing one, the ID sometimes appears selected instead of its corresponding value (for example, '5' instead of "apple"). It seems like the value is being set before the combo finishes loading.

Is there a solution to this problem? Below is the code snippet that creates the combos:

function createDictionaryCombo(store, fieldLabel, hiddenName, name, allowBlank, myTooltip) {
      combo = {
        xtype: 'combo',
        id: 'id-' + name,
        allowBlank: allowBlank,
        fieldLabel: fieldLabel,
        forceSelection: true,
        displayField: 'value',
        valueField: 'id',
        editable: false,
        name: name,
        hiddenName: hiddenName,
        minChars: 2,
        mode: 'remote',
        triggerAction: 'all',
        store: store
     };

    function createDictionaryJson(url) {
      store = new Ext.data.JsonStore({ 
        root: 'results', 
        fields: ['id', 'value'],
        url: url,
        autoLoad: true
      });

      return store;
    }

    var comboKarStore = createDictionaryJson('/service/karok');
    var comboKar = createDictionaryCombo(comboKarStore, 'Kar', 'karid', 'kar', false, '');

    // then comboKar is added to the form

Hubidubi

Answer №1

ksjdflmao your approach is quite effective. I personally find using a plugin for my combos to be the best option. Give it a shot, it works flawlessly for me. Simply add the following code snippet to bind it to a combo:

plugins: new Application.plugins.comboloadvalue(),

Add this to your combo configuration object.

Ext.ns('Application.plugins');

Application.plugins.comboloadvalue = Ext.extend(Ext.util.Observable, {
field : null,

init : function(field){
    var self = this;
    this.field = field;
    this.store = field.getStore();
    this.setLoaded(false);

    this.store.on('load', function(){
        return self.onLoad();
    }, this);
},

onLoad : function(){
    if(this.store !== null){
        this.field.setValue(this.field.getValue());
        this.setLoaded(true);
    }
    return true;
},

setLoaded: function(bool){
    this.store.hasOnceLoaded = bool;
},

getLoaded: function(){
    return this.store.hasOnceLoaded;
}

});

Answer №2

It is important to remember that stores loading remote data operate asynchronously. Therefore, it is crucial to process the store data within the appropriate callback function to ensure that it is ready for use. For example:

let selectionStore, comboSelectionStore = makeJsonDictionary('/api/selection');

comboSelectionStore.on('load', function(){
    selectionStore = createCombo(selectionStore, 'Selection', 'id', 'name', false, '');
});

Answer №3

Here is a clever workaround that ensures compatibility with all combinations:

Implement this workaround before loading any combinations (it doesn't have to be after the document is ready)

Ext.form.ComboBox.prototype.nativeSetValue = Ext.form.ComboBox.prototype.setValue;
Ext.form.ComboBox.prototype.setValue=function(v){
   var combo = this;
   if(this.valueField){
      var r = this.findRecord(this.valueField, v);
      if (!r) {
         var data = {}
         data[this.valueField] = v
         this.store.load({
            params:data,
            callback:function(){
               combo.nativeSetValue(v)
            }
         })   

      } else return combo.nativeSetValue(v);
   } else combo.nativeSetValue(v);
}          

This functionality checks whether your value exists in your store, and if not, initiates a callback with valueField = value before attempting to set it again. Ensure your serverside handler recognizes "query" for searches and the key field for loads.

Additionally, this method works well with "search" type combos that may have a loaded store but incorrect records.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Confidently set up a proxy that is recursively nested and strongly typed

I have a collection of objects where I store various content for a user interface. Here is an example: const copy = { header: { content: 'Page Header' }, main: { header: { content: 'Content Subheader' }, body ...

Following the implementation of the YITH ajax navigation filter, my jQuery scripts are no longer functioning as

I'm having trouble with using yith ajax navigation in my theme. Everything works perfectly until I click on an element to filter, at which point my jquery codes stop working. The team at yith suggests: If your product list contains JavaScript cod ...

Returning to the previous page is done by navigating back using the previous URL in Next.js

Recently, I encountered a situation where I had implemented filters on a webpage. Upon applying the filters, the URL of the page would change and additional query strings would be appended to the end. This caused an issue when navigating back using the b ...

Is it possible to JSON serialize Django Querysets that have been processed with the values method? I'm curious if there are any

The issue at hand is that Django's serializer does not support dictionaries while simplejson does not support Django Querysets. For further details, refer to JSON Serializing Django Models with simplejson I am uncertain if my current approach is corr ...

Encountered an issue when trying to add the value "BIT" into MySQL through Nifi PutDatabaseRecord because of a data truncation error

Struggling to set up a mirrored database for Mysql using CaptureChangeMysql. When attempting to replicate a table with a "BIT" data type column, encountering an error related to data truncation. The column "status" in the source database is of type "BIT" ...

Developing a custom camera system for a top-down RPG game using Javascript Canvas

What specific question do I have to ask now? My goal is to implement a "viewport" camera effect that will track the player without moving the background I am integrating websocket support and planning to render additional characters on the map - movement ...

How can one ensure that the "DataTables" Jquery Plugin has been properly initialized?

One of the challenges I face is having multiple DataTables-Objects within a Form. Is there a way to verify if all of them are initialized correctly? This verification is crucial for me as I rely on Ajax for submitting the form. ...

Obtaining data with jQuery.Ajax technology

I am attempting to retrieve real-time data from a different URL and display it in a text field every second without refreshing the entire page. The content of the URL is constantly changing, so I want the field to update accordingly. However, despite my ef ...

The Vue JS Option element requires the "selected" attribute to be utilized as a property instead

I'm attempting to automatically have an option selected if the "selected" property is present on the option object. Here is my code snippet: <template> <select v-model="model" :placeholder="placeholder"> <option v-for="opt ...

Having trouble displaying real-time camera RTSP streaming using Angular

I am currently in the process of developing a web application using Angular and I need to incorporate a window that displays live RTSP streaming. Upon conducting research, I discovered that this can be achieved by utilizing the JSMpeg JavaScript library. ...

I am uncertain about whether it would be better to utilize URL path parameters or query parameters for filtering on the back-end of the application

Suppose I am trying to retrieve all car models from a specific brand. This can be achieved by utilizing URL path parameters or query parameters as shown below: router.get('/modelsByBrand', modelController.getModelsByBrand); To make the GET reque ...

In Bash scripting, it is not possible to replace a command line variable

I'm currently working on a small command line script designed to send a json body to an http server using curl. However, I've encountered an issue trying to pass the first command line argument ($1) to the json body. #!/bin/bash curl -X POST -d ...

KnexJS raw query yielding unexpected results

I need help with the following issue: SET @count = 0; UPDATE table SET table.id = @count:= @count + 1 WHERE table.name = "name"; When I run this query through tools like Jetbrains Datagrip, it works fine. However, when I use Knex to execute it as a raw q ...

Is it possible to generate a vendor bundle for CSS/Sass in Vue.js CLI 3?

I am currently using @vue/cli 3.x and I made some changes to my vue.config.js. I am looking to have separate CSS files like app.css and vendor.css (compiled from Sass) - similar to how it handles JavaScript. However, I am unsure about the correct configura ...

Sending transaction proposals in Hyperledger Fabric involves passing arguments as JSON format when invoking the chaincode using the sendTransactionProposal function

When calling a chaincode in Go Lang through the Fabric Node.js API, I have encountered an issue with the Request Object for the method sendTransactionProposal(req ChaincodeInvokeRequest). The ChaincodeInvokeRequest only accepts arguments as an Array for ...

Error Module in Angular 1.4.2: $injector:modulerr

I have exhausted all the solutions available on StackOverflow and other sources, but none of them seem to work for me. I have ensured that all scripts are loaded properly. I am using Visual Studio 2015 and trying to create a menu using Mobile Angular Ver ...

Switch between class and slider photos

I am currently having an issue toggling the class. Here is the code I am working with: http://jsfiddle.net/h1x52v5b/2/ The problem arises when trying to remove a class from the first child of Ul. I initially set it up like this: var len=titles.length, ...

Library for adjusting the x axis scaling accurately

I need to find a JavaScript chart library that can support lines and zooming for handling a large amount of data. One issue I have encountered with other libraries is scaling the x-axis based on date and time data provided in strings: y=[43,56,34,63....] ...

How can I create a more spacious and stylish JTextField for my address bar?

I am working on developing my Java skills by creating a custom browser. Is there a way to adjust the size and shape of the address bar, which is currently implemented as a JTextField with Swing's default settings? Here is the code snippet I am using: ...

When the button is clicked, a modal will pop up

Looking for help in incorporating JavaScript to create a responsive modal that pops up with lyrics when a button is pressed in a table. Any assistance would be greatly appreciated. Note: Only the code for the table has been provided. Let me know if you&ap ...