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

The BlazeDS Flex-AJAX Bridge fails to function properly when integrated with Ext.JS

When utilizing the FDMSLib for the Flex-AJAX bridge, a load function is called that renders a flash object to the page. However, conflicts arise when using Ext.JS as the inserted object may be discarded by another render function or cause rendering conflic ...

Maintain parental visibility with children when navigating to a different page

I am currently working on a vertical accordion menu that opens on hover, stays open, and closes when other items are hovered. The great assistance I received from @JDandChips has been instrumental in getting this feature up and running. Now, my main focus ...

CSS Code Failing to Adjust Inner Components Width in Variable Table

I'm facing an issue while trying to create an excel-style table using HTML and CSS. The problem arises when I attempt to have a varying number of columns in different rows, as the table exceeds the border limit and expands on its own. My goal is to re ...

Is it possible to make an AJAX request even when the server file (such as PHP) is missing?

While working on the Sharetronix script, I encountered something unusual. In the console, I noticed that a network request was being sent to the following address: http://localhost/ajax/postform-submit/ajaxtp:xml/r:0 However, I couldn't locate any f ...

The jQuery selector fails to refresh after the dynamic insertion of new elements

My selector is: $('section#attendance input:last') However, I add another input to section#attendance. I want the selector to target that new element since it should select the last element due to :last. However, for unknown reasons, it does no ...

The npm command encountered a permission issue when trying to install node-sass

Whenever I run the npm command on my Ubuntu system, I encounter a "permission denied" issue. sudo npm install node-sass EACCES: permission denied, access '/node_modules/node-sass' I have attempted to run the command as a root user or with sudo ...

Using knex.js to pipe data to an express server

I'm encountering an issue with knex.js and express. Here is the code snippet in question: userRouter.get('/:userId', function (req, res) { DB('users').where({ id: req.params.userId }).first('name').pipe(res); }); ...

Save property using the useState hook

I am working on implementing a sorting function in the child component, where the props are passed in from the parent through an axios call. Should I: Store the prop in the child component's useState? Pass the parent's setState function as a pro ...

I am having trouble with PHP/Ajax "Vary: X-Requested-With" not working for my specific needs

I am attempting to deliver cacheable content based on whether it is an AJAX request or not. Here's the situation: A small PHP script, "/test.php," provides some HTML output and sets the following headers: Expires Wed, 23 Feb 2011 13:30:06 G ...

Express (generator) is failing to load custom scripts located in the public folder

I'm new to node and express and I'm facing a problem. I want to load a custom script.js from the public folder, but it's not loading. There are no errors in the console or anything in the network tab. When I try to access the URL localhost:3 ...

Converting JSON into Typescript class within an Angular application

As I work on my app using angular and typescript, everything is coming together smoothly except for one persistent issue. I have entity/model classes that I want to pass around in the app, with data sourced from JSON through $resource calls. Here's ...

Breaking down a statement into individual elements within an array, incorporating keys alongside the elements within the array

let condition = "[AccNum]==true&&[AccNum]==[ARID]&&[AccNum]==aaaa || [ARID]!=true&&[DOB]>[ARID] || [DOB]>bbb&&[DOS]>=[ARID]&&[DOS]<[Gender]&&[66642]<=cccc&&[66642] I ...

Using XMLHttpRequest with gzip compression

Utilizing the request module in node.js makes it simple to create a request that can retrieve and correctly decompress compressed data from the source: var request = require('request'); var requestOptions = { url: 'http://whatever.com/g ...

A guide on displaying a text file from a URL in a reactjs application

When utilizing the code provided below, I have successfully managed to display the content of a local text file on a webpage. However, when attempting to render a text file from a URL, the state becomes null resulting in an empty display. In order to ren ...

The node experiences a crash when the redis-server goes offline

Struggling with a persistent issue here. Despite reading numerous documents and posts from others on the same topic, I can't seem to find a solution to prevent this problem. I am intentionally shutting down the redis server to avoid potential disaster ...

JSON object representing a nested class

I am facing an issue while attempting to create a JSON object using JavaScript/jQuery. Specifically, I am trying to get the JSON object for Class A and encountering problems with the value of b1 being undefined. Class A { string test1; B b1; } Class B { ...

Dynamic options can now be accessed and modified using newly computed getters and setters

When using Vuex with Vue components, handling static fields that are editable is easily done through computed properties: computed: { text: { get() { return ... }, set(value) { this.$store.commit... }, }, }, <input type ...

Employing ajax with dynamically created buttons in PHP

I'm struggling to figure out what to search for in this situation. I've tried piecing together code from others, but it's just not working for me. My ajax function successfully retrieves data from a database through a php page and displays ...

Keep an ear out for updates on object changes in Angular

One of my challenges involves a form that directly updates an object in the following manner: component.html <input type="text" [(ngModel)]="user.name" /> <input type="text" [(ngModel)]="user.surname" /> <input type="text" [(ngModel)]="use ...

Brochure displaying shattered tiles using ionic

Whenever I try to load a map using Ionic, it keeps displaying broken tiles. No matter if I load directly from Leaflet or use bower, the issue persists. Even when using pure leaflet code without any special directives, those broken tiles are still there. ...