This is a migrated thread and some comments may be shown as answers.

Dynamic column list based on user role

3 Answers 299 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Zebenzui
Top achievements
Rank 1
Zebenzui asked on 27 Jan 2020, 01:17 PM

Hi ,

 I am working on a some prototypes for my workplace and I am looking for guidance on the best approach. I am relatively new to Kendo and have recently switched from the mvc helpers to Jquery + javascript. I am trying to do the following. My sample code is below.

 

1. I would like to dynamically generate the cols on the UI using the remote result set. So the result set may contain 25 cols but I only want to paint 5 of them

2. I would like to implement this in reasonably straight forward manner. I was hoping that I could use the datasource fetch but now am no so sure.

3. I would remove the columnheader menu and install my own drop down in the grid toolbar which I would then use to toggle the grid columns on and off. I could then control what columns this would be performed for.  I have to do this as there is a restriction on using child grids and frozen cols

 

 

The issue that I am encountering is the grid is rendered before I have chance to modify what gets renedered and how. I have seen suggestions that one should destroy the grid prior to rebuilding it.  So can you 

 

A.) Indicate if I should create fetch request outside a datasource and use my custom ajax call or should I rebuild the datasource each request

B.) Destroy the grid at each request 

B.) Do you have any examples in js where this is done. I have search the web and founds bits and pieces. 

 

Thanks

Ciaran

 

 

 

 

 

<div id="container">
    <div id="grid"></div>
</div>
<script type="text/javascript">
var baseurl ="http://localhost:5000/api/"
var currentModel; 
var requiredColumns=["Id", "CoreId"]
var showOnlyTheseColumns =["Id", "CoreId", "projectName" ]
var DEFAULT_PAGE_SIZE = 15;
var isDateField =[];
var currentColumns =[];
var currentFilters = [];
currentFilters.push({field: 'Id',operator: 'contains',value: '22' });



$(function(){
         var grid =   $("#grid").kendoGrid({
                dataBound: function(e) {
                    var grid = this;
                    console.debug('Its too late here its already bound..');
                },
                dataBinding: function(e){
                    let grid = this;
                    grid.columns() =[];                
                    console.debug('databinding called');
                },
                autoBind: true,  //!!! PRETTY SURE THIS SHOULD BE SET TO FALSE. Is this correct? !!!
                height: 400,
                toolbar: kendo.template($("#toolbarTemplate").html()),
                columns:currentColumns,
                pageable: {
                    buttonCount: 6,
                    refresh: true,
                    pageSizes: [20, 50, 100, 200],
                    messages: {
                        display: "Showing {0}-{1} from {2} " ,
                        empty: "No records to display",
                        itemsPerPage: " per page",
                    }
                },
                sortable: true,
                filterable: true,
                scrollable: true,
                reorderable: true,
                resizable: true,
                editable: true,                
                dataSource: {
                    serverPaging: true,
                    serverFiltering: true,
                    serverSorting: true,
                    pageSize: DEFAULT_PAGE_SIZE,
                    sort: {
                        field: "J.CoreId",
                        dir: "desc"
                    },
                    schema: {
                        data: "data",
                        total: "total",
                        model: currentModel
                    },
                    batch: false,
                    transport: {
                        create: {
                            url: baseurl +"Job",
                            contentType: "application/json",
                            type: "POST"
                        },
                        read: {
                            url: baseurl +"Job",
                            contentType: "jsonp",
                            complete: function (qXHR, textStatus) {
                                console.log(textStatus, "update");

                                //Build the model from the source data
                                currentModel = generateModel(qXHR.responseJSON.data);
                                //create the columns from the source data
                                currentColumns =generateColumns(qXHR.responseJSON.data);
                                console.log('ITS TOO LATE THE GRID IS ALREAYD BOUND ')
                                $('#grid').data('kendoGrid').refresh();

                            }
                        },
                        update: {
                            url: baseurl +"Job",
                            contentType: "application/json",
                            type: "PUT"
                        },
                        destroy: {
                            url: baseurl +"Job",
                            contentType: "application/json",
                            type: "DELETE"
                        },
                        parameterMap: function (data, operation) {
                            currentColumns =[];                            
                            return JSON.stringify(data);
                        }
                    }
                }
            });
        });
</script>

<script type="text/javascript">
// https://docs.telerik.com/kendo-ui/knowledge-base/create-with-dynamic-columns-and-data-types
function generateColumns(gridData){
        for (var property in gridData[0]) {
            if (showOnlyTheseColumns.indexOf(property) > -1){
                currentColumns.push({field: property,width: "100px", format: (isDateField[name] ? "{0:D}" : "")});
            }
        } 
        return currentColumns;
}

3 Answers, 1 is accepted

Sort by
0
Zebenzui
Top achievements
Rank 1
answered on 28 Jan 2020, 02:07 PM

Hi ,

 I believe I have figured it out . Not sure. Code is below. I am going to have to destroy the grid each time I repaint it I think . Can you confirm if this is correct. Also can you point to a real world example of dynamic grids with kendo jquery UI. All examples I see to date are fixed columns . 

 

 

    griddataSource.fetch(function(){
        var data = griddataSource.data();
        var myfields =generateModel(data);
        var grid = $("#grid").kendoGrid({
            dataSource: {
                data: data,
                schema: {
                    model: {
                        fields: myfields.fields
                    }
                }
        },
        sortable: true,
        filterable: true,
        groupable: false,        
        pageable: {
                    refresh: true,
                    pageSizes: true,
                    buttonCount: 5
        },
        scrollable: true,
        editable: false,
        toolbar: kendo.template($("#toolbarTemplate").html()),
        columns: generateColumns(data)
        }).data("kendoGrid");
    });

0
Angel Petrov
Telerik team
answered on 29 Jan 2020, 09:32 AM

Hi Zebenzui,

Actually it seems that you have all the parts. One thing that is left is to re-generate the grid when new data with different set of columns is fetched. For that purpose one can use the setOptions method. If we take the code provided so far you can do the following.

function recreateGrid() {
           var grid = $("#grid").getKendoGrid();

           var data = // here should be the new data;
           var myfields = generateModel(data);

          grid.setOptions({
              dataSource: {
                  data: data,
                  schema: {
                      model: {
                          fields: myfields.fields
                      }
                  }
              },
              columns: generateColumns(data)
          })
       }

Note that the above will re-create the grid entirely, however this can not be avoided when changing the column structure.

Regards,
Angel Petrov
Progress Telerik

Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
0
Zebenzui
Top achievements
Rank 1
answered on 29 Jan 2020, 10:11 AM
Thanks
Tags
Grid
Asked by
Zebenzui
Top achievements
Rank 1
Answers by
Zebenzui
Top achievements
Rank 1
Angel Petrov
Telerik team
Share this question
or