Dynamic Data in the Kendo UI Grid_870x220

Learn how to create Kendo UI grids with dynamic data in this step by step recipe.

The moment you find yourself typing the same code over and over again, you know that something is off. You know that the code you are writing is getting WET (Write Everything Twice or We Enjoy Typing).

You need to stop, plan, modularize and DRY it off. You will thank yourself later when the next grid is up in seconds and you are sipping on that cup of coffee you have been thinking of all afternoon.

Creating editable Kendo UI Grids with dynamic data is like cooking an a-la-carte meal the easy way. As a Technical Support Engineer at Progress, I have seen plenty of our clients' "kitchens," helped resolve questions and given advice regarding dynamic data—and I am here to give you the recipe.

The Dynamic Data Recipe Kendo UI Chef
Ready in about 1 hour
Medium level skills
Serves: 1 editable and 1 non-editable grid


Ingredients

1. Consistent Backend Service and API
2. One initial ajax request
3. Client Grid Configuration
4. Client Data Source Configuration

Method

1. Create a backend with consistent naming of the controller actions. For example:

  • READ
    http://domain/Orders
           http://domain/Customers       
  • CREATE
    http://domain/Orders/Create
      http://domain/Cutomers/Create  
  • UPDATE
    http://domain/Orders/Update
    http://domain/Customers/Update
  • DELETE
    http://domain/Orders/Destroy
    http://domain/Customers/Destroy

2. (This step applies to a read-only grid—for an editable grid, go to step 3.) Naturally, a read-only grid requires less complex logic. I created a simple function, called in the success handler of the initial ajax request. It adds some common options and its data source needs only the read operation.

    // add the grid options here 
    function populateGrid(response) {
        var columns = generateColumns(response);
        var gridOptions = {
          dataSource: {
            transport:{
              read:  function(options){
                options.success(response);
              }
            },
            pageSize: 10,
            page: 1
          },
          columns: columns,
          pageable: true,
          height:300
        };

        // reuse the same grid, swapping its options as needed
        var grid = $("#grid").data("kendoGrid");
        if(grid){
          grid.setOptions(gridOptions);
        } else {
          $("#grid").kendoGrid(gridOptions);
        } 
      }
  
Since I do not want the "ID" column to take up much space, I created another the generateColumns function so I can alter the columns configuration. You can customize all the columns properties at this point.
  function generateColumns(response){
        var columnNames = Object.keys(response[0]);
        return columnNames.map(function(name){
          var isIdColumn = name.indexOf("ID") > -1 || name.indexOf("Id") > -1;
          return { 
            field: name,
            width: isIdColumn ? 50 : 180,
            title: isIdColumn ? "Id" : name
          };
        })
      }

Voilà! The read-only Kendo UI Grids with dynamic data are ready to be thrown in the oven. To show you how easy it is to use the functions above, I added a Kendo UI ToolBar with three buttons. When each button is pressed, the click function populates the respective Kendo UI Grid.

To open as an editable Dojo, hover over the right hand top corner     ⬎ 

3. To create a dynamic editable Kendo UI Grid, we need to create the dataSource schema model before the dataSource. In the success callback of the initial ajax request, pass a sample dataItem to the generateModel function. The function accomplishes two very important tasks:

Checks the type of each property so the grid can initialize the correct editor. For example, the number type will create a Kendo UI NumericTextBox, the date type will be equipped with a Kendo UI DatePicker when in edit mode.
Finds the unique schema model id and makes it non-editable. The unique id is a prerequisite for the editing functionality.

The function can be extended to include other schema model settings such as validation and default value. Or you may collect the field names of date types, so they can be formatted in the column settings later on.

 
      var dateFields = [];
      
      function generateModel(sampleDataItem) {
        var model = {};
        var fields = {};
        for (var property in sampleDataItem) {
          if (property.indexOf("ID") !== -1) {
            model["id"] = property;
          }

          var propType = typeof sampleDataItem[property];
          if (propType === "number") {
            fields[property] = {
              type: "number"
            };
            if(model.id === property){
              fields[property].editable = false;
            }
          } else if (propType === "boolean") {
            fields[property] = {
              type: "boolean"
            };
          } else if (propType === "string") {
            var parsedDate = kendo.parseDate(sampleDataItem[property]);
            if (parsedDate) {
              fields[property] = {
                type: "date"
              };
              dateFields[property] = true;
            }
          }
        }

        model.fields = fields;

        return model;
      }
    

4. Now that we have the schema model, we can create the Kendo UI Data Source. The function should receive the base URL and the model as parameters. Since the services follow a naming convention, it is easy to create this dynamic data source with CRUD operations:

      
    function generateDataSource(baseURL, model) {
         var dataSource = {
          transport: {
            read: {
              url: baseURL
            },
            create:{
              url: baseURL + "Create"
            },
            update:{
              url: baseURL + "Update"
            },
            destroy:{
              url: baseURL + "Destroy"
            },
            parameterMap: function(options, operation) {
              if (operation !== "read" && options.models) {
                return {models: kendo.stringify(options.models)};
              }
            }
          },
          batch:true,
          schema: {
            model:model
          },
          pageSize: 10
        };

        return dataSource;
      }
    

 

5. Next in line are the grid columns. Use this function to customize the formatting, width or other columns settings

      
      function generateColumns(sampleDataItem) {
        var columnNames = Object.keys(sampleDataItem);
        return columnNames.map(function(name) {
          var isIdField = name.indexOf("ID") !== -1;
          return {
            field: name,
            width: (isIdField ? 40 : 200),
            title: (isIdField ? "Id" : name)
          };
        });
      }
    

 

6. This is the final step. The schema, data source and columns are known and we can initialize the dynamic Kendo UI Grid. In my function, I am passing the id of the element from which I will initialize the grid but you can extend the createGrid function and append the newly generated grid elsewhere.

      
      function createGrid(gridName, baseUrl) {
        $.ajax({
          url: baseUrl,
          success: function(response) {
            var sampleDataItem = response[0];
            var model = generateModel(sampleDataItem);
            var dataSource = generateDataSource(baseUrl, model, editable);
            var columns = generateColumns(sampleDataItem);
            var gridOptions = {
              toolbar: ["create", "save", "cancel"],
              dataSource: dataSource,
              columns: columns,
              pageable: true,
              editable: editable,
              height: 450
            };

            columns.push({ command: "destroy", title: " ", width: 170 });

            $("#" + gridName).kendoGrid(gridOptions);
          }
        });
      }
    
The result—initialization of a dynamic editable grid with a single line of code:

    <div id="products"></div>
    <script>
      createGrid("products", "https://demos.telerik.com/kendo-ui/service/products/");
    </script>

To open as an editable Dojo, hover over the right hand top corner    

This is just a basic dynamic data in the Kendo UI Grid recipe. There is much more than that which can be done, extended and plugged in as required. The examples I created here can be reused, saving you time and effort. The investment that one needs to make is well worth the payback when many similar grids need to be created—a naming convention, an extra single ajax request and coding a more abstract backbone logic so it can be reused.

If you already have your own Kendo UI Grid with dynamic data, please share what you do differently in the comments section below.


Alex Hajigeorgieva
About the Author

Alex Hajigeorgieva

Alex Hajigeorgieva is a Technical Support Engineer II working on Kendo UI. She likes scuba diving, volleyball and studying new technologies. 

Related Posts

Comments

Comments are disabled in preview mode.