Ext Js Tree

August 8, 2007 | In: tutorials

Jack Slocum and the guys over at Ext JS labs have delivered in my humble opinion one of the best JavaScript UI libs I have ever had the pleasure to work with.

They have a particularly nice tree widget that I’ve leveraged a few times using Json rendered from rails. This page is the only one I’ve found that explains how to populate it from rails and it leverages acts_as_nested_set. I found that to be a bit of overkill (and in Japanese or something) so I did an alternate version which uses acts_as_tree instead.

Here’s hoping this saves someone some time… Enjoy :)

In your Model:

  acts_as_tree

In your controller:

  def get_tree_data
    folders = Folder.find(:all)
    data = get_tree(folders)
    render :text=>data.to_json, :layout=>false
  end

In your application controller:

 def get_node(obj)
   if obj.children.empty?
     return [{"text"=>obj.name,"id"=>"#{obj.class}_#{obj.id}","cls"=>"#{obj.class}_node".downcase,"leaf"=>true}]
   else
     return [{"text"=>obj.name,"id"=>"#{obj.class}_#{obj.id}","cls"=>"#{obj.class}_node".downcase,"leaf"=>false}]
   end
end

def get_tree(collection)
  data = Array.new
  collection.each { |item|
    if data.empty?
      data = get_node(item)
    else
      data.concat(get_node(item))
    end
  }
  return data
end
Bookmark and Share
  • Hi

    thanx for the help...

    but how to u send Json object from view to the javascript...i mean, how to do u use it with Jstree
blog comments powered by Disqus

Flickr Pics

13th and washington NYC13th and 9th NYC1st st Jersey CityIMG_2813IMG_2814_2IMG_2816IMG_2815Photo_011908_001Photo_122807_001Photo_121107_001