56

Dynamic Options in the Kendo UI Grid

 5 years ago
source link: https://www.tuicool.com/articles/hit/veaqeyA
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Whether you have just started usingKendo UIor are already pretty proficient with our widgets and main concepts, you know as well as I do, as does anyone in our industry - things change. Every. Time. You. Blink.

So in this blog post, I intend to show you some tips and tricks on how to make your users' experience more personal, more dynamic and most importantly - of a better quality. To deliver a personalized and improved experience there are three key points to focus on when building aKendo UI Gridwith dynamic options:

User Defined Configuration

How can you equip the admin users with editing functionality and deny it to regular users in the same grid?

In the busy world that we live in an adaptive UI becomes a necessity, but how do you provide for it and keep all the goodness of the web experience that the Kendo UI Grid has to offer?

The runnable demo.

People love being in control so why not give it to them? Instead of decorating the Kendo UI Grid like a Christmas tree, with all the available features and functionalities, why not create some custom UI that allows the users to pick and choose ? Not only will users be able to choose their configuration but it may bring them better performance because they will enable only what they will use.

I like this point the best, because it is in line with the Extreme Programming principle You Ain't Gonna Need It (Y.A.G.N.I. for short). It is easy to forget that in the background a whole bunch of magic needs to take place, widgets initialized and handlers attached when all one needs to type is reorderable:true . But why have a reorderable grid if it is not needed?

One of the frequently asked questions about a Kendo UI Grid with dynamic options is: How to grant administrator rights to some users and deny it to others?

The most straightforward way is to obtain the user role before creating the grid and dependent on the role, pass the desired configuration options. However, remember that user permissions should be handled on the server, so don't rely on the client user permissions alone.

The Kendo UI Grid has a mobile* configuration option that makes working on smaller screens/touch enabled devices easier. The grid creates a separate view for editing and filtering the column menu, and enables native scrolling where possible. If you have not seen our adaptable demos in action, you may do sohere. They look the best on real mobiles and tablets but the browser's device mode can also give you a good idea.

If you like the look and feel of the adaptive Kendo UI Grid, you can initiate it dynamically with the help of the nifty API of the kendo.support utility namespace. It can help determine the device type and OS version, the browser, scrollbar, transitions and transformations and other things which you may find helpful.

*Before deciding whether to use the adaptive grid, visit the documentation. It may look like the web grid but it is quite different.

The Demo

For best UX and testing, see the demo in full screen on web and hybrid devices here

The Step by Step Instructions

  • Create the custom UI. I used the Kendo UI styled radio buttons whose value is the option value for the sake of ease and simplicity. Also, using JSON.parse() parses the true and false strings to their correct boolean counterparts, so that's one gotcha it avoids. Any string which is not an empty string will evaluate to true, e.g.: Boolean("false") === true
    <input type="radio" name="selectable" id="selectable-multi" class="k-radio"  value='"multiple,row"'>
        <label class="k-radio-label" for="selectable-multi">Multiple Selection</label>
        <input type="radio" name="selectable" id="selectable" class="k-radio"  checked="checked" value="false">
        <label class="k-radio-label" for="selectable">No Selection</label>
    So later you can obtain the radio selected options like this:
    var radioSelectedOptions = {
           selectable: JSON.parse($("[name='selectable']:checked").val())
         };
  • Radios and checkboxes are not a real world example, so to complicate matters a little, I also added aKendo UI Listbox which allows for adding extra options. I structured its dataItems to help me map them to the configuration option the grid expects - the text is the dataTextField the users see as the option and the value is the dataValueField which matches the grid configuration options we will pass:
    var listBoxDs = [{
              text: "Column Menu",
              value: { columnMenu : true}
            }, {
              text: "Excel Export",
              value: {
                excel: {
                  allPages: true
                }
              }
            }];
    Next is the task to get the the radio selected options and the listbox options and merge them. For example:
    var lbOptions = selectedOptions.dataItems()
         .toJSON()
         .reduce(function(optionsObj, item) {
           for (var key in item.value){
             optionsObj[key] = item.value[key];
           }
           return optionsObj;
         }, {});
         
         var selectedGridOptions = kendo.deepExtend(lbOptions, radioSelectedOptions);
  • Finally, you can initialize the grid with the selected options, if the grid has already been initialized, use the setOptions() method to change the options and reset the data source with the shorthand query() method:
    var grid = $("#grid").data("kendoGrid");
            if(grid){
              grid.dataSource.query({
                filter: [],
                group:[],
                sort:[],
                page: 1,
                pageSize:20
              });
              grid.setOptions(mergedOptions);
            } else {
              $("#grid").kendoGrid(mergedOptions);
            }
  • You will need to keep a set of default options because the setOptions() method makes an internal call to get the current options, then deep extends them with the new options. So if the user had set a pageable grid initially, then removed that setting, the pager will linger and will not go away unless you set it to false explicitly. Here is a list of the defaults used in the demo:
    var defaultOptions = {
              mobile: isMobile,
              toolbar: [],
              groupable:false,
              pageable:false,
              resizable:false,
              columnMenu:false,
              navigatable:false,
              reorderable:false,
              scrollable:true,
              persistSelection:false,
              sortable:false,
              dataSource: dataSource,
              height: 550,
              columns: [
                { field:"ProductName", width: 200},
                { field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: 180 },
                { field: "UnitsInStock", title: "Units In Stock", width: 150 },
                { field: "Discontinued", width: 180 }
              ]
            }
  • The multiple selection does not work on mobile devices because there is no way to distiguish if the user wishes to scroll or select. So you can check if the grid is used on such device and instead of using the built-in multiple selection, add a selectable column .
    if(isMobile && selectedGridOptions.selectable && selectedGridOptions.selectable === "multiple,row"){
         selectedGridOptions.selectable = false;
         defaultOptions.columns.splice(0,0,{ selectable:true, width: 30 });
        }
  • The Excel and PDF options should be added to the toolbar. The default empty array we set earlier will come in handy to add the save changes and create buttons for CRUD operations. If the user removes these options, the toolbar will have no tools thanks to the default empty array. The edit/destroy commands dependent on the editable mode need to be added to the grid columns configuration. You may move these commands to be the first column and provide a different mode of editing for users on mobiles, for example:
    if(selectedGridOptions.pdf){
              defaultOptions.toolbar.push("pdf");
            }
    
            if(selectedGridOptions.excel){
              defaultOptions.toolbar.push("excel");
            }
    
            if(!isMobile && selectedGridOptions.editable){
              var editTools = ["create", "save", "cancel"];
              defaultOptions.toolbar = defaultOptions.toolbar.concat(editTools);
              defaultOptions.columns.push({ command: "destroy", title: " ", width: 150 });
            } 
            
            // inline or popup editing provides better UX on a mobile 
            if(isMobile && selectedGridOptions.editable){
              selectedGridOptions.editable.mode = "inline"; 
              selectedGridOptions.editable.confirmation = false;
              var editTools = ["create"];
              defaultOptions.toolbar = defaultOptions.toolbar.concat(editTools);
              defaultOptions.columns.splice(0,0,{ command: ["edit", "destroy"], title: " ", width: 150 });
            }
  • When changing the options, reset the data source as well, otherwise, a grouped grid data source will remain grouped even if the user removes the groupable option, a sorted grid will remain sorted and the same is true for the paging and filtered states.
    grid.dataSource.query({
             filter: [],
             group:[],
             sort:[],
             page: 1,
             pageSize:20
           });

Summary

I hope this blog will inspire you to look for ways to give your users a better and more personal experience of using the Kendo UI Grid. While the idea of "one size fits all scenarios and devices" seems like a fairy tale, we get one step closer by getting personal - using the information that we know - the user type, the device and browser they are using and allowing them to choose what they need.

If there is anything in particular that you want ourKendo UIteam to blog about, please mention it in the comments or in our Feedback Portal. We would love to hear from you.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK