Extjs: How to Select a Node After Creating a Tree Structure

I am facing an issue with my TreePanel where I want to preselect a specific node when loading it. The nodes are fetched from a remote json file and the tree structure loads correctly. However, the selected node is not getting highlighted and Firebug is showing the node as undefined. I suspect this could be due to the async property but I am unable to find a workaround or specify the node to be selected programmatically.

If you have any suggestions or solutions for this problem, please feel free to share them. Thank you in advance.

    LeftMenuTree = new Ext.tree.TreePanel({
    renderTo: 'TreeMenu',
    collapsible: false,
    height: 450,
    border: false,
    userArrows: true,
    animate: true,
    autoScroll: true,
    id: 'testtest',
    dataUrl: fileName,
    root: {
  nodeType: 'async',    
     iconCls:'home-icon',
     expanded:true,
       text: rootText
    },
    listeners: {
        "click": {
    fn: onPoseClick,
                 scope: this
               }
        },
          "afterrender": {
       fn: setNode,
       scope: this 
      }  
 });
function setNode(){
 alert (SelectedNode);
  if (SelectedNode == "Orders"){
    var treepanel = Ext.getCmp('testtest');
    var node = treepanel.getNodeById("PendingItems");
    node.select();
  }
} 

Answer №1

This snippet of code is utilized in the TreeGrid to highlight a specific node

_I.treeGrid.getSelectionModel().select(_I.treeGrid.getRootNode());

While I have not personally tested this in a TreePanel, as the TreeGrid is built on it, I would assume it functions properly. I employed a similar approach by using the load event of the loader to execute comparable code after the XHR request was finished. Therefore, when creating your setNode function, consider structuring it like this:

var loader = LeftMenuTree.getLoader();
loader.on("load", setNode);    
function setNode(){
     alert (SelectedNode);
      if (SelectedNode == "Orders"){
        var treepanel = Ext.getCmp('testtest');
        treepanel.getSelectionModel().select(treepanel.getNodeById("PendingItems"));
      }
    }

Answer №2

It worked perfectly for me...

var search  = Ext.getCmp('searchBox').getLoader();
search.on("load", function(x,y,z){ 
   y.findChild("id",1, true).select(); // can locate by any attribute in the dataset
}); 

Answer №3

If you're looking for a solution similar to this, I have detailed the steps in achieving it right here:

http://www.example.com/achieve-something-similar-with-extjs

Ensure that the node you are selecting is visible by traversing the tree and expanding all its parent nodes starting from the root down.

Answer №4

The reason behind this issue is that the node cannot be selected until the tree is fully rendered. To solve this problem, consider attaching your node selection logic to an event listener that triggers upon the completion of rendering.

Answer №5

If you are utilizing a sufficiently recent version of ExtJS, I personally find that utilizing ViewModels and the Selection configuration makes tasks like this much simpler.

For example:

LeftMenuTree = new Ext.tree.TreePanel({
renderTo: 'TreeMenu',
collapsible: false,
height: 450,
border: false,
userArrows: true,
animate: true,
autoScroll: true,
id: 'testtest',
dataUrl: fileName,
bind: {
    Selection: '{SelectedNode}'
}, 
root: {
   nodeType: 'async',    
   iconCls:'home-icon',
   expanded:true,
   text: rootText
},
listeners: {
    "click": {
       fn: onPoseClick,
       scope: this
    }
    "afterrender": {
       fn: setNode,
       scope: this 
    }  
 });

(Make sure to have either a ViewModel established in the TreePanel or the containing view)

Assuming you are using a ViewController and setNode is a method:

setNode: function(){
 var nodeToSelect = // code to locate the node object here
 this.getViewModel().set('Selection', nodeToSelect);
} 

The benefit of the ViewModel approach is that it appears to seamlessly handle all rendering and data loading matters automatically.

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

I am encountering a "TypeError: topics.forEach is not a function" error when attempting to retrieve metadata for topics using my kafkajs client in Node.js/express.js. Can anyone help me understand why

I am attempting to retrieve the metadata of my Kafka brokers' topics using the kafkajs admin client within my Node.js + express.js server. Here is the content of my index.js file, serving as the main entrypoint for npm: 'use strict'; cons ...

Data not maintained when page is reloaded

I am in the process of implementing a login panel on my index page. The login data will be sent via an ajax call. Upon successful verification of the username and password, I am storing the user data in a session and then reloading the index page upon ajax ...

The validation errors in the form of CodeIgniter are not being displayed by the JavaScript variable

Currently, I am utilizing the built-in validation_errors() function in CodeIgniter for my login form. The validation errors are displaying correctly in my view, but when I try to echo them into a JavaScript variable within the script to customize notificat ...

Enhance your website with unique and custom fonts using

I am utilizing this repository. How can I incorporate custom fonts into my project? I have created a folder named "fonts" within the assets directory and placed my fonts there. fonts.scss @font-face { font-family: 'Lato'; src: url('../ ...

Using Javascript to test a specific item in an asp Listbox

Let's consider a scenario where there is ListBox1 containing the following listitem: <asp:ListItem Value="No.1">No.1</asp:listitem> In addition, we have a label for a test purpose: <asp:Label ID="lblLabel" runat="server" Text="Label ...

How to retrieve an array value within a function in AngularJS

<select class="form-control" id="column" ng-model="selectedcolumn" ng-options="column for column in columns"></select> <input type="text" ng-model="test[selectedcolumn]" ng-change="search()" /> Is there a way to retrieve the value o ...

What are the steps for initializing a session in Vue.js with Django upon a successful login?

Upon successful login, I want to redirect to a page indicating success and also include a session. How can this be achieved? I am using HTML with Vue.js for the front end and Django for the back end. Below is my Vue.js script for the login: <script> ...

Changing letter cases in a textbox using Javascript

I have a challenge to create a code that can switch the case of text entered by the user. Here is what I currently have: var num; function toggleTextCase(str) { return str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase( ...

React powered interactive tables

I am in the process of creating a dynamic table using React, and here is the data structure I am working with: { numRows: 2, numCols: 3, cells: [ { id: 1, pos: { row: 1, col: 1 }, content: 'This is th ...

Using React: Implementing conditional checks within the render() method of functional Components

When working with my usual React class Components, I typically perform some checks within the render() method before returning conditional html rendering. However, when using a react functional component, I noticed that there is no render() method availabl ...

How to incorporate user-submitted form data into the existing state using React

I am currently working on a React project that involves a form input. The goal is for the user to input a number into the field, and then take that number and add it to another number in the application's state. For example, if this.state.data initia ...

invalid audio element

I'm currently working on building an audio player with a visualizer feature. However, when I try to initiate the audio player by clicking on the input button, my debug console keeps showing this error message: Uncaught (in promise) DOMException: Fa ...

`The error "mockResolvedValue is not recognized as a function when using partial mocks in Jest with Typescript

Currently, I am attempting to partially mock a module and customize the return value for the mocked method in specific tests. An error is being thrown by Jest: The error message states: "mockedEDSM.getSystemValue.mockResolvedValue is not a function TypeEr ...

Ways to determine if prototype methods vary

Is there a technique to verify if functions are distinct despite originating from the same prototype? I'm inquiring because I want to save functions in an array, and when attempting to delete one, it removes all functions due to sharing prototypes. ...

JavaScript code to copy a specified column through the last column, and then paste it down to the last row

I have limited experience with JavaScript and I've been putting together the code I need by searching online resources and watching videos. My goal is to set multiple columns in row 4, starting from column 18 to the last column, as the active cells fo ...

Looking to design an interactive grid for generating dynamic thumbnails

I am a beginner in the field of web development and I have a desire to create a website for showcasing my portfolio. This website should feature project thumbnails along with brief descriptions, all of which should be displayed dynamically. Although I poss ...

Sharing a Promise between Two Service Calls within Angular

Currently, I am making a service call to the backend to save an object and expecting a number to be returned via a promise. Here is how the call looks: saveTcTemplate(item: ITermsConditionsTemplate): ng.IPromise<number> { item.modifiedDa ...

Trigger Vue method when the size of a div element changes

Is there a way to trigger a method every time the dimensions (width or height) of a div element change? <template> <div> </div> </template> <script> export default { methods: { updateSize() { // ...

What is the best way to use Jquery to enclose a portion of a paragraph text within a

How can I wrap the content inside a span that comes after another span, inside a paragraph and a new span? To further illustrate this, consider the following example: <p>foo <span>bar</span> baz</p> The desired outcome is: <p& ...

Comparing NodeIntegration, Preload Script, and IPC in Electron Framework

After thoroughly going through Electron's explanations on context isolation, IPC, and security, as well as delving into discussions like this thread about nodeIntegration and this post regarding preload.js, it's clear that there are various appro ...