Telerik Forums
Kendo UI for jQuery Forum
1 answer
65 views

Morning,

I've been using the Kendo Grid for years and absolutely love it for what I can do with it, but every so often I get asked to stretch the functionality of what it can do,  I haven't found much documentation on this, but i'll try my best to give an example of what I've done, and to see if there is a better way of doing it..

I have a field in my Grid that is a string, with multiple "Tags" explicitly given in the dataSource in filterable.

    {
        "columnMenu": {
            "componentType": "modern"
        },
        "stickable": true,
        "field": "conditions",
        "filterable": {
            "enabled": true,
            "multi": true,
            "search": true,
            "dataSource": [
                {
                    "conditions": "TEST123"
                },
                {
                    "conditions": "TEST"
                },
                {
                    "conditions": "ABC"
                },
                {
                    "conditions": "DEF"
                }
            ]
        },
        "groupable": true,
        "aggregates": "count",
        "groupHeaderTemplate": "Conditions: #= value # (Count: #= count#)",
        "sortable": true,
        "title": "Conditions",
       

The data in the field is a string of comma separated tags, i.e.

TEST, ABC, DEF

I've updated the filter method on the Grid so that I can select multiple options in the filter menu, and it does a "contains" look up to match multiple hits.

filter: function(e){
	this.columns.forEach(function(f){
		if(e.field === f.field){
			if(f.filterable.hasOwnProperty('dataSource')){
				e.filter.filters.forEach(function(f){
					f.operator = "contains";
					e.filter.logic = "and";
				})
			}
		}
	})
},

I have two issues here.

1. I'm using contains, so if the tags are similar (TEST, TEST123), selecting TEST will show both TEST and TEST123 - which isn't ideal.

2. If I select an option from the filter menu, it doesn't remain checked if you were to go back into the filter menu again.

I've asked this question before and had some great help to get it to this point using: https://docs.telerik.com/kendo-ui/knowledge-base/grid-how-to-change-multi-checkbox-filter-to-contains but I'm wondering if there is a better way of achieving the functionality I'm looking for here with the grid.  I added square brackets to the tags to distinguish them ([TEST], [TEST123]) , but my users didn't like this change.

Is there a way to do this without using contains?

I'd also like to be able to see the selected option in the filter menu - I can find the checkbox through jQuery, but I cannot toggle it's state..

e.filter.filters.forEach(function(f){
	var checkbox = $(".k-filter-menu").find("input[value='"+f.value+"']");

	console.log(checkbox);												 
        checkbox.prop("checked", true).trigger("change");
	checkbox.attr("checked", true).trigger("change");

	f.operator = "contains";
	e.filter.logic = "and";
})

Thanks for your help,

Matt

Martin
Telerik team
 answered on 05 Feb 2024
1 answer
22 views

Hello Teacher:

          My front-end code:

var dataSource = new kendo.data.DataSource({
                type: "aspnetmvc-ajax",
                pageSize: 25000,
                serverPaging: false,
                serverGrouping: false,
batch: true,
                transport: {
                    read: {
                        url: urlRead,
                        data: kendo.antiForgeryTokens(),
                        type:"GET"
                    },

                    create: {
                        url: urlCreate,
                        data: kendo.antiForgeryTokens(),
                        cache: true,

                    },
                    update: {
                        url: urlUpdate,
                        data: kendo.antiForgeryTokens(),
                        cache: true,
                    },
                    destroy: {
                        url: urlDestroy,
                        data: kendo.antiForgeryTokens(),
                        cache: true
                    },

                    parameterMap: function (data, type) {
                        //if (type == "create") {
                        //    // send the created data items as the "models" service parameter encoded in JSON
                        //    return { models: kendo.stringify(data.models) };
                        //}
                    }

                },
                //requestStart: function() {
                //    kendo.ui.progress($("#"+gridName), true);
                //},
                //requestEnd: function() {
                //    kendo.ui.progress($("#"+gridName), false);
                //},
                sync: function (e) {


                },
                schema: {
                    data: "Data",
                    total: "Total",
                    errors: "Errors",
                    model: model,
                    errors: function (response) {
                        //ShowNotification(response);
                        return response.error;
                    }
                },
                error: function (e) {
                    //ShowNotification("Error");
                    dataSource.cancelChanges();
                }
            });
            //dataSource.bind("error", function () { ShowNotification("dsError") });

            grid.setOptions({
                dataSource: dataSource,
                persistSelection: true,
                navigatable: true,
                resizable:true,
                reorderable:true,
                dataBound: function (e) {
                    if (e.sender.dataSource.view().length > 0) {
                        e.sender.select("tr:eq(0)");
                        grid.trigger("change");
                        grid.unbind("dataBound");
                    }

                }
            });

Processing data in batches, I don't know how the frontend sends backend requests and how the backend receives requests?

                                        
Neli
Telerik team
 answered on 06 Dec 2023
1 answer
35 views
Hi Team,

In kendo grid jquery I have added data to a data Source in JSON format. In this format, there is a property in the JSON. If that property is true, I want to change the color of the row. Is it possible to set a different color?

gridData = @Html.Raw(ViewData["DataDetailsJson"]);


var dataSource = new kendo.data.Data Source({
    data: gridData,
    batch: true,
    autoSync: true,
    schema: {
        model: {
            id: "uid",
            fields: {
                id: { hidden: true },
                Project: { editable: false },
                User: { editable: false },
                Status: { editable: false },
            },
        },
    },
});
Neli
Telerik team
 answered on 29 Nov 2023
1 answer
23 views

Like the title says, my grid doesn't "call home" on row deletion... read/update/create work just fine (and all go to the same .aspx on the server).

Here's my (edited slightly) code:

var sThisPage = location.pathname.substring(location.pathname.lastIndexOf("/") + 1);

 

$("#divGrid").kendoGrid({ columns: [ { field: 'Department1', title: 'Department', width: 100, editable: telerik_grid_column_onEditable, editor: deptDropDownEditor, template: "${displayDept(Department1)}", }, { field: 'EmployeeID', title: 'Employee', width: 200, editable: telerik_grid_column_onEditable, editor: emplDropDownEditor, template: "${displayEmpl(EmployeeID)}", }, { field: 'SecurityLevel', title: 'Security level', width: 100 }, { field: 'EmplActive', title: 'Active', width: 80, template: "#= EmplActive ? '<span class=\"fa-solid fa-check\"></span>' : '' #" }, ], dataSource: new kendo.data.DataSource({ serverPaging: false, serverFiltering: false, serverSorting: false, //autoSync: true,

requestStart: function (telerikEvent) { }, requestEnd: function (telerikEvent) { }, sync: function (telerikEvent) { var oToolbar = $("#divToolbar").data("kendoToolBar"); var oFirstLine = this._data[0]; if (!oFirstLine.ID || oFirstLine.ID == '') { //First line is a new recordif ((!oFirstLine.Department1 || oFirstLine.Department1 == '') || (!oFirstLine.EmployeeID || oFirstLine.EmployeeID == '') || (!oFirstLine.SecurityLevel || oFirstLine.SecurityLevel == '' || oFirstLine.SecurityLevel == 0)) { alert('New line not saved as some values are missing.'); } } oToolbar.enable("#btnSave", false); oToolbar.enable("#btnCancel", false); }, error: function (e) { if (e.xhr) { alert(e.xhr.responseText); } $("#divGrid").data("kendoGrid").cancelChanges(); }, transport: { read: { url: sThisPage, type: "POST", dataType: "json", cache: false, data: { action: "R" } }, update: { url: sThisPage, type: "POST", dataType: "json", cache: false, data: { action: "U" } }, create: { url: sThisPage, type: "POST", dataType: "json", cache: false, data: { action: "C" } }, destroy: { url: sThisPage, type: "POST", dataType: "json", cache: false, data: { action: "D" } }, }, schema: { model: { id: "ID", fields: { Department1: { type: "number" }, EmployeeID: { type: "number" }, DeptName: { type: "string" }, EmployeeName: { type: "string" }, SecurityLevel: { type: "number", validation: { required: true, min: 1, max: 100 } }, EmplActive: { type: "boolean", editable: false }, } } }, }), editable: true, sortable: true, selectable: "row", change: telerik_grid_onChange, beforeEdit: telerik_grid_onBeforeEdit, edit: telerik_grid_onEdit, cellClose: telerik_grid_onCellClose, remove: function (telerikEvent) { var x = telerikEvent; this.dataSource.sync(); }, });


function telerik_toolbar_button_onClick(telerikEvent) {
	var x = telerikEvent;
	var oGrid = $("#divGrid").data("kendoGrid");
	
	switch (telerikEvent.id) {
/*snip*/
		case 'btnDelete':
			var oSelected = oGrid.select();
			oGrid.removeRow(oSelected);
			break;
	}
}	//telerik_toolbar_button_onClick

If I set breakpoints on the requestStart and requestEnd functions in the data source and delete a line, neither gets hit.

 

Am I doing something wrong?


Eric
Top achievements
Rank 1
Iron
 answered on 17 Nov 2023
0 answers
37 views

i have controller using java as @RequestMapping("/charts") and it return in Json format but my question this data is not reflected in my Grid why. 

 $("#grid").kendoGrid({
                        dataSource: {
                           
                    transport: {
                         read: {
                             url: function(options) 
                             {   return "${pageContext.request.contextPath}/charts";
                                         },
                            
                            dataType: "json",
                            type: "GET"
                        }
                        },
                            
                            schema:{
                                model: {
                                    fields: {
                                        id: { type: "number" },
                                        fullName : { type: "string" },
                                        address: { type: "string" },
                                        email : { type: "string" },
                                        password: { type: "string" },
                                        designation: { type: "string" },
                                        salary: { type: "number" }
                                    }
                                }
                            },

                            aggregate: [ { field: "fullName", aggregate: "count" },
                                
                                          { field: "salary", aggregate: "sum" }
                                          ]
                             
                       ,pageSize: 8 },
                        sortable: true,
                        scrollable: false,
                       pageSize: 5,
                       pageSizes: true,
                        hieght:20,
                         pageable: {
                
           pageSizes: [4, 6,10,"all"],
           buttonCount: 5
                },
     columns: [
                   { field: "id", title: "ID", width: 180  },
                   { field: "fullName", title: "Name",width:300,
                    template: "<div style=color:red>#=fullName#</div>" ,footerTemplate: "Total Count: #=count#"  },
                     { field: "address", title: "Address",width:300 },
                      { field: "email", title: "Email",width:200},
                      { field: "password", title: "Password" ,width:200},
                            { field: "designation", title: "Designation" ,width:300},
                            { field: "salary", title: "Salary" ,width:200,footerTemplate: "Total Sum: #=sum#"},
                            { width:200,
                              template: "<a class='k-button' href='/Home/Index'>Redirect</a>"   }
                            
                        ]
                    });

kha
Top achievements
Rank 1
Iron
Iron
 asked on 22 Oct 2023
1 answer
42 views

Hi,

 

For some reason when I try to add a new record to my dataSource ….then refresh the grid  for my hierarchical table that uses detailInit,

 

…. the formatting is bypassed for my new record added to the dataSource.

 

 

After I add the new data to the JavaScript array... and refresh the grid, it does repopulate the child or detail grid:

 

 

But it doesn't appear to catch the format: "{0:c}"

 

 

I don't know why the new value (monetary) is getting bypassed with the format option? Here is my code for the detailInit(e):

 


functiondetailInitMainGrid(e) { console.log("IN: detailInitMainGrid()"); var payCodeList = []; var data = _view.get("interimDS.interimPayrollRecords"); //DEBUG:var data2 = e.data; $.each(data, function (index, value) { if (value.payCode != 'Total') { // add NON-TOTAL records to data array//DEBUG://console.log(" LAST NAME:" + value.fullName + " : RECORD ID: " +value.interimPayrollRecordId); payCodeList.push({ interimPayrollRecordId: value.interimPayrollRecordId, payCode: value.payCode, amount: value.amount, amountHrsMins: value.amountHrsMins, monetary: value.monetary, }); } }); console.log("event data source: ID:" + e.data.interimPayrollRecordId + ", NAME: " + e.data.fullName); //var detailCell = e.detailCell;//detailCell.css("padding-left", "350px"); $("<div/>").appendTo(e.detailCell).kendoGrid({ dataSource: { data: payCodeList, serverPaging: false, serverSorting: false, serverFiltering: false, filter: { field: "interimPayrollRecordId", operator: "eq", value: e.data.interimPayrollRecordId } }, scrollable: true, sortable: true, pageable: false, columns: [ { field: "payCode", title: "Pay Code", width: "110px", attributes: { class: "child-table-details" } }, { field: "amount", title: "Amount<br/>(HRS)", width: "50px", format: "{0:n}", attributes: { class: "child-table-details" } }, { field: "amountHrsMins", title: "Amount<br/> (HRS:MIN)", width: "50px", attributes: { class: "child-table-details" } }, { field: "monetary", title: "Monetary<br/>Amount", width: "50px", format: "{0:c}", attributes: { class: "child-table-details" } } ] }); }

 

I did  manage to debug through the creation of the child table (in the detailInit(e) function) when I click the little triangle on the left of the parent record, but it seems to bypass the new value I pushed to the JavaScript array structure and prints it out with our the $ or the trailing .00. I don't want to create a custom formatter in javascript, I think the format option for the monetary column should be working... but maybe there is something I am doing that causes it to malfunction or convert it to the monetary or currency format?

Thanks again for your help and patience,

George

 

George
Top achievements
Rank 2
Iron
Iron
Iron
 updated answer on 13 Oct 2023
1 answer
53 views

I am trying to bind it with dynamic columns SQL table paging. The issue is on the second scroll/page it failed the method.

Razor Page

@model System.Data.DataTable
@(Html.Kendo().Grid<dynamic>()
    .Name("Grid")
    .Sortable()
    .Scrollable(sc => sc.Endless(true))
    .Filterable()
    .Groupable()
        .DataSource(dataSource => dataSource
            .Ajax()
            .PageSize(100)
            .Model(model =>
            {
                var id = "Id";
                model.Id(id);
            })
            .Read(read => read.Action("Data_Read", "DynamicColumn"))
        )
)

Controller DynamicColumn

 public IActionResult Data_Read([DataSourceRequest] DataSourceRequest request)
 {
     var dt = GetViewsData(request.PageSize, request.Page);
     var data = dt.ToDataSourceResult(request);
     var viewData = new DataSourceResult()
     {
         Data = data.Data, //this return NULL on the second page/scroll request
         Total = 181480 //total rows of table, just make it static
     };
     return Json(viewData);
 }

public DataTable GetViewsData(int pageSize, int page)
    {

        try
        {
            int offSet = (page - 1) * 100;
            string connString = "Server=.; Database=TheVault_VMC; Trusted_Connection=true; MultipleActiveResultSets=True; Encrypt=False;";
            SqlConnection con = new SqlConnection(connString);
            con.Open();
            SqlCommand cmd = new SqlCommand("sp_GetData", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@OFFSetRows", offSet);
            cmd.Parameters.AddWithValue("@PageSize", pageSize);
            SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
            var dataTable = new DataTable();

            dataAdapter.Fill(dataTable);
            dataAdapter.FillSchema(dataTable, SchemaType.Mapped);
            con.Close();
            return dataTable;

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

}


SQL Server Procedure

CREATE PROCEDURE [dbo].[sp_GetData] 
   @OFFSetRows INT,
   @PageSize INT
As
BEGIN    
SELECT Id, [Column1], [Column2], [Column3],[Column4],[Column5],[Column6]
FROM
[StagingDetail]
ORDER BY Id
OFFSET @OFFSetRows ROWS
FETCH NEXT @PageSize ROWS ONLY
END

 

The issue is the function ToDataSourceResult() returns NULL Data on the second request
Anton Mironov
Telerik team
 answered on 13 Sep 2023
1 answer
47 views

I have a kendo grid in JSTL format where I'm trying to override a filter choice for date (making the filter look for the span of an entire day like in this example. But setting a simple hardcoded filtergives no results in the kendo grid, even when there are results matching the filter:

let startOfFilterDate = new Date(2000,1,1,0,0,0) 
let endOfFilterDate = new Date(2000,1,1,23,59,59) 
var filter = { 
  logic: "and", 
  filters: [ 
    { field: "date", operator: "gte", value: startOfFilterDate }, 
    { field: "date", operator: "lte", value: endOfFilterDate } 
  ] 
}; 
e.sender.dataSource.filter(filter);

I've tried putting in various places...

1) <kendo:dataSource-change></kendo:dataSource-change

2) <kendo:grid name="search-result-grid" ... filterable="true" columnMenu="true" columnMenuInit="doFilter">

And then my "doFilter" method is pretty much the same as the given example linked to above.

If I console.log the dataSource.filter, it shows that the filters are there. But the datasource is not being updated/refreshed with the filter for whatever reason.

Georgi Denchev
Telerik team
 answered on 30 Aug 2023
1 answer
87 views

Hello, I am studying a lot because I am using Kendo for JQuery for the first time in this project.

Currently, I am creating a function that registers a favorite for each row of data, and I need to create it as shown in the picture.

The favorite column is assigned a Y/N cutoff value, and the icon changes accordingly.

And when the icon is clicked, the icon should change if the favorite status is successfully switched through ajax communication.

Thanks a lot for all your help!

Ruchika
Top achievements
Rank 1
Iron
 answered on 03 Aug 2023
0 answers
81 views

¿Alguien ha trabajado con esto? Tengo configurado el web service y me esta retornando el json que debe leerme y mostrarme en el grid, pero no consigo realizar que se visualicen los datos 

 

 

 

<body>
    <div id="grid"></div>
    <script>
        $(document).ready(function () {
            const dataSource = new kendo.data.DataSource({


                dataSource: {
                    type: "odata",
                    transport: {
                        read: "http://localhost:53072/Service.svc/ObtenerDatos"
                    },
                    pageSize: 20
                },
                schema: {
                    model: {
                        fields: {
                            Id: { type: "number" },
                            Nombre: { type: "string" },
                            Precio: { type: "number" }
                        }
                    }
                },
                pageSize: 10
            });

            $("#grid").kendoGrid({
                dataSource: dataSource,
                height: 400,
                sortable: true,
                pageable: true,
                columns: [
                    { field: "Id", title: "ID" },
                    { field: "Nombre", title: "Nombre" },
                    { field: "Precio", title: "Precio" }
                ],

            });
        });
    </script>
</body>

andres
Top achievements
Rank 1
 asked on 13 Jul 2023
Narrow your results
Selected tags
Tags
+? more
Top users last month
Mark
Top achievements
Rank 1
Yurii
Top achievements
Rank 1
Leland
Top achievements
Rank 2
Iron
Iron
Iron
Hon
Top achievements
Rank 1
Iron
Deltaohm
Top achievements
Rank 3
Bronze
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Mark
Top achievements
Rank 1
Yurii
Top achievements
Rank 1
Leland
Top achievements
Rank 2
Iron
Iron
Iron
Hon
Top achievements
Rank 1
Iron
Deltaohm
Top achievements
Rank 3
Bronze
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?