Getingt to Know the new Kendo UI DropDownTree_870x220

The DropDownTree UI component is a new addition to Kendo UI that allows you to easily display hierarchical data rendered as a tree structure within a dropdown element. Read on to learn how you can use it in your apps.

One of my favorite things coming out of the R2 2018 release of Kendo UI for jQuery is the new DropDownTree component. This component was the top-voted feedback item in the Kendo UI feedback portal and I was pumped to see this widget be a part of the release. A lot of you have already started using the component, but I wanted to take some time going through a little introduction of the component, as well as some of the top features, for folks that have not yet had a chance to add this widget to their apps!

This blog post specifically covers the jQuery edition of the DropDownTree. If you're looking to use this component with HTML or Tag Helpers in ASP.NET MVC or ASP.NET Core I recommend reading this blog post by Ed Charbeneau.

Getting Started with the DropDownTree

First off, what is the DropDownTree all about? Well, as someone that spends a lot of time plugging in data in to forms I feel that sometimes nothing beats a drop down component. This is a fairly clean user experience since it takes up so little space, but once we enter or click on the component the data found within the component can be a huge list of items. In some cases we want the list to represent our underlying data, which could be in hierarchical form. What's a good way to display hierarchical data? You guessed right: a TreeView.

This is where the DropDownTree comes in to play. Hierarchical data rendered as a tree structure found within a drop down.

With that out of the way, let's see how we can go about implementing this component.

To kick things off we are almost always working with an input element when we're looking to input data in our forms, even with dropdowns, so let's create one for our DropDownTree.

<input id= "dropdowntree" />

Now, since we're dealing with jQuery we can instantiate our Kendo UI component like we would do with any other Kendo UI widget.

$(document).ready(
  function () {
    $("#dropdowntree").kendoDropDownTree();
  }
);

We're not going to get anywhere without data and for this example we'll just hard code the items we want to be able to select.

$(document).ready( function () {
  $("#dropdowntree").kendoDropDownTree({
    dataSource: [
      {
        text: "DC",
        expanded: true,
        items: [
          { text: "Batman" },
          { text: "Wonder Woman" },
          { text: "Hawkgirl" }
        ]
      },
      {
        text: "Marvel",
        items: [
          { text: "Deadpool" },
          { text: "Silver Surfer" },
          { text: "Black Panther" }
        ]
      }
    ]
  });
});
Note the expanded: true property on the "DC" node. This allows a node to be automatically expanded whenever the dropdown opens. This is set to false by default.

There are a couple more configuration options that we can set to make this component a little easier to interact with and a bit more friendly, specifically the height (sets the height of the internal TreeView), autoClose (allows us to prevent closing the drop down when selected), and placeholder (text to be displayed when an item has not been selected) options. I'll just throw in the entire piece of code along with these properties right here:

<div id= "example">
  <input id= "dropdowntree" />
  <script>
    $(document).ready( function () {
      $("#dropdowntree").kendoDropDownTree({
        placeholder: "Select your hero...",
        height: "auto",
        autoClose: false,
        dataSource: [{
          text: "DC",
          expanded: true,
          items: [
            { text: "Batman" },
            { text: "Wonder Woman" },
            { text: "Hawkgirl" }
          ]
        },
        {
          text: "Marvel",
          items: [
            { text: "Deadpool" },
            { text: "Silver Surfer" },
            { text: "Black Panther" }
          ]
        }]
      });
    });
  </script>
</div>

This all results in the following DropDownTree:

DropDownTree Component with DC and Marvel characters as options

Working with Remote Data

The sample we just stepped through gives us a good idea of how to get started with the DropDownTree, but what about some more real-life scenarios? For example, what if we want to bind to a REST API somewhere rather than deal with local data? Well, if you noticed above we have the DataSource configuration option built-in to the component and this means we can easily work with a Kendo UI HierarchicalDataSource (this is hierarchical data after all).

In the Kendo UI documentation and demos we have a few sample endpoints that we can use, but in this particular case I'll use a URL that we almost always use for homogeneous data, namely this URL: https://demos.telerik.com/kendo-ui/service/Employees.

If we plug this in to our browser or Postman we see that the response we get at the initial level is the following:

callback([{ "EmployeeId" :2, "FullName" : "Andrew Fuller" , "HasEmployees" : true , "ReportsTo" : null }])

This means we have a single item at the root level, and we probably should pay attention to the HasEmployees field to see if an item should be expandable or not.

So, to hook into this we first need to create our data source. As we do this we also need to do two things:

  1. Define a client-side model of the data source that defines a unique identifying field
  2. Define the field that indicates if the item has children or not (to help query deeper for more data)

With this in mind we come up with the following code:

var sampleData = new kendo.data.HierarchicalDataSource({
  transport: {
    read: {
      url: " https://demos.telerik.com/kendo-ui/service/Employees",
      dataType: "jsonp"
    }
  },
  schema: {
    model: {
      id: "EmployeeId" ,
      hasChildren: "HasEmployees"
    }
  }
});

Now, configuring the DropDownTree to use this HierarchicalDataSource instance is pretty easy. Taking from our previous example we just define the DataSource to use sampleData and then we set the dataTextField configuration option to indicate which field is responsible for displaying text.

$("#dropdowntree").kendoDropDownTree({
  placeholder: "Select ...",
  height: "auto",
  autoClose: false,
  dataSource: sampleData,
  dataTextField: "FullName"
});

That's all there is to it! Here's a quick view of what the end-result looks like.

DropDownTree bound to remote employee data

Useful Features

Beyond just binding to data (local or remote) there are a ton of fun features available out of the box as well. Here's a couple of my favorites that are extremely useful and can be enabled with just a few configuration options.

Checkboxes

Everyone loves some checkboxes! Previously we've just dealt with single selection, but if we want to allow our users to select multiple elements with ease we can do so with simple checkboxes.

Taking our super heroes example we can just tweak the code and add in two configuration options: checkboxes and checkAll. The first option is pretty self-explanatory, while the second option gives us a "Check All" item

<div id="example">
  <input id="dropdowntree" style= "width: 200px;" />
  <script>
    $(document).ready( function () {
      $("#dropdowntree").kendoDropDownTree({
        placeholder: "Select your hero...",
        height: "auto",
        autoClose: false,
        checkboxes: true,
        checkAll: true,
        dataSource: [{
          text: "DC",
          expanded: true,
          items: [
            { text: "Batman" },
            { text: "Wonder Woman" },
            { text: "Hawkgirl" }
          ]
        },
        {
          text: "Marvel",
          items: [
            { text: "Deadpool" },
            { text: "Silver Surfer" },
            { text: "Black Panther" }
          ]
        }]
      });
    });
  </script>
</div>

This is how it ends up looking. Note the tokens that we create when we select items that can easily be removed from the input itself instead of deselecting an item after opening the component.

DropDownTree with check box selection

Client-Side Filtering

If we're dealing with a lot of data it's nice to work with some way of filtering down the total number of items that we're displaying. This is why we implemented the filter configuration option. This is a single configuration option that can be set to "startswith", "endswith", or "contains" to tweak how the filtering is done. Here's our super hero DropDownTree with a "startswith" filter set.

DropDownTree with a starts with filter of "B"

Templates

The last neat filter that I want to highlight is the ability to define a template within the DropDownTree. This uses the Kendo UI template framework in order to define an external filter using HTML and then using this to define just how each item should look beyond just a simple node with text or a check box.

Here's a quick look at what can be accomplished with templates.

DropDownTree with custom templates for each node

This image was taken from our online template demo which showcases the full source code for how to implement something like this.

Go Forth and Dropdown

There you go folks - an introduction along with my favorite parts of the DropDownTree! I hope you enjoyed this look in to this great new component. Who knows, maybe you were inspired to add it in to your application? There's more to this component than what I've covered here, so I recommend that you look at the Kendo UI online demos as well as the DropDownTree API section of our documentation. As always, if you have any feedback around how we can improve the component with new features and functionality you can leave us a comment here or head over to the Kendo UI feedback portal!


carl-bergenhem
About the Author

Carl Bergenhem

Carl Bergenhem is the Product Manager for Kendo UI. Throughout his time at the company he’s covered the entire portfolio of products offered, but mainly spent his time in the web development arena covering ASP.NET Ajax, ASP.NET MVC, and JavaScript-based products. He’s passionate about web technologies and has been developing with products like Kendo UI and NativeScript since their inception. In his free time Carl enjoys slaying virtual monsters, snowboarding and playing his guitar.

Related Posts

Comments

Comments are disabled in preview mode.