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

Set grid values of cell based on selected row criteria

14 Answers 522 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Bill
Top achievements
Rank 1
Bill asked on 26 Apr 2019, 10:13 PM

Hi All,

I created a simple project using the Telerik grid template.  In my script, I update "Freight" to zero for the selected row.   However, I want to set ALL ROWS that match the CustomerID of the selected row to zero.

  Here are the peices:

VIEW

@{
    ViewData["Title"] = "Home Page";
}
 
<div class="row">
    <div class="col-xs-18 col-md-12">
        @(Html.Kendo().Grid<TelerikAspNetCoreApp3.Models.OrderViewModel>()
                .Name("grid")
                .Selectable()
                .Editable(editable => editable.Mode(GridEditMode.InCell))
                .Events(events =>
                {
                    events.Change("onSelectedRow");
                })
                .Columns(columns =>
                {
                    columns.Bound(p => p.CustomerID)
                        .ClientGroupHeaderColumnTemplate("CustomerID");
                    columns.Bound(p => p.OrderID);
                    columns.Bound(p => p.Freight);
                })
                .Pageable()
                .DataSource(dataSource => dataSource
                    .Ajax()
                    .PageSize(20)
                    .Read(read => read.Action("Orders_Read", "Grid"))
                    .Group(groups =>
                    {
                        groups.Add(g => g.CustomerID);
                    })
                    .Model(model =>
                    {
                        model.Field(p => p.OrderID).Editable(false);
                        model.Field(p => p.CustomerID).Editable(false);
                    })
                )
            )
        )
    </div>
</div>
<script>
    function onSelectedRow(e) {
        var gview = $("#grid").data("kendoGrid");
        var selectedItem = gview.dataItem(gview.select());
        var custId = selectedItem.CustomerID;
        //I want to update ALL freight fields to 0 where CustomerID equals custId, not just the selectedItem
        selectedItem.set("Freight", 0);  //Fix or update this to update all rows
    }
</script>

MODEL

namespace TelerikAspNetCoreApp3.Models
{
    public class OrderViewModel
    {
        public int OrderID {get;set;}
        public double CustomerID{get;set;}
        public decimal? Freight{get;set;}
    }
}

CONTROLLER

namespace TelerikAspNetCoreApp3.Controllers
{
    public class GridController : Controller
    {
        public ActionResult Orders_Read([DataSourceRequest]DataSourceRequest request)
        {
            var result = Enumerable.Range(0, 50).Select(i => new OrderViewModel
            {
                CustomerID = (i+100)/10,
                OrderID = i,
                Freight = i * 10
            });
            var dsResult = result.ToDataSourceResult(request);
            return Json(dsResult);
        }
    }
}

 

If this is completely the wrong approach, I'll take ideas for a better/easier solution.

Thank you in advance!

14 Answers, 1 is accepted

Sort by
0
Eyup
Telerik team
answered on 29 Apr 2019, 07:33 AM
Hello Bill,

As mentioned in the following article, when setOptions is called, the Grid widget will be destroyed and recreated:
https://docs.telerik.com/kendo-ui/api/javascript/ui/grid/methods/setoptions

This means that not everything will be kept the same, especially custom styling or templates. Would it be acceptable to you if we change the column header titles manually instead?

Regards,
Eyup
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
Eyup
Telerik team
answered on 29 Apr 2019, 07:42 AM
Hi Bill,

Sorry, this was for another case. 

The answer to your question is yes - this is possible and can be achieved using the following approach:

1. Use the Change event handler (already done)

2. Access the ID of the row - e.g. CustomerID

3. Traverse the items collection of the grid:
https://docs.telerik.com/kendo-ui/api/javascript/ui/grid/methods/items

4. Inside the for loop, you can change the Freight value of each item. You can try using the set method for that or this alternative approach:

- open the cell in edit mode:
https://docs.telerik.com/kendo-ui/api/javascript/ui/grid/methods/editcell
- change the value of the input element explicitly
- close the cell:
https://docs.telerik.com/kendo-ui/api/javascript/ui/grid/methods/closecell

Give this solution a try and let me know about the result.

Regards,
Eyup
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
Bill
Top achievements
Rank 1
answered on 29 Apr 2019, 06:22 PM

Hello Eyup,

I have reviewed the references you provided.   I am unclear how I can limit the freight update to only those rows that match the customerId.   Using grid.items() selects all grid items whereas I only want to select/update those freight values that match CustomerId.  How do I use selectedCustId to cull the grid.items() list?   I'm getting warmer using this:

function onSelectedRow(e) {
    var gview = $("#grid").data("kendoGrid");
    var selectedCustId = gview.dataItem(gview.select()).CustomerID;
    var allRows = gview.items().each(function () {  
        var data = gview.dataItem(this);
        if (data.CustomerID == selectedCustId) {
            gview.select(this);
        }
    });
    gview.select(allRows);

This selects the "SelectedRow" and the first row of the group that matches CustomerId.  But before I can work on updating the freight field, I need to get all the matching customerId's selected.

 

0
Eyup
Telerik team
answered on 30 Apr 2019, 03:04 PM
Hello Bill,

You can achieve this requirement using the following approach:
https://dojo.telerik.com/ONaDAWaR/6

I hope this will prove helpful.

Regards,
Eyup
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
Bill
Top achievements
Rank 1
answered on 30 Apr 2019, 11:11 PM

Hi Eyup,

I think I'm really close.   I couldn't figure out how to use the set method to update the cell cuz I think it redraws the grid after the first change.   Anyway, I have it doing most of what I want.   There is one more problem-  after I select a row, all other rows that have the same parent ID (in my case this is 'attributeId') are set to zero and the selected row then sets a new value.   This all works,  But, when I do the save changes, the zero'd items are not flagged as dirty and as such do not update.   How do I set all the cells of interest (that match the attribute ID) to be dirty so that they are updated?

<script>
    function onRowSelected(e) {
        var grid = e.sender;
        var items = grid.items();
        var selectedItem = grid.dataItem(grid.select());
        for (var i = 0; i < items.length; i++) {
            if (grid.dataItem(items[i]).AttributeId == selectedItem.AttributeId) {
                $(items[i]).addClass("k-state-selected");
            }
        }
        var cellsToChange = grid.select();
        for (var i = 0; i < cellsToChange.length; i++) {
            var item = grid.dataItem($(cellsToChange[i]).closest("tr"));
            item.ItemValue = "0"; //these cells should show as dirty and be updated on save changes
        }
        selectedItem.set("ItemValue", selectedItem.ScalePosition);
        grid.refresh();
    }
</script>
0
Eyup
Telerik team
answered on 02 May 2019, 08:52 AM
Hello Bill,

You can try the open/change/close method suggested in my previous reply to achieve that. 
If the issue still remains, you can modify the provided dojo sample to demonstrate the problem and send it back to us so we can provide more precise solution.

Regards,
Eyup
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
Bill
Top achievements
Rank 1
answered on 03 May 2019, 12:11 AM

Hello Eyup,

If I understood how to implement the references you provided earlier I would have.  Referencing them again doesn't help me.  I am sorry I do not understand better.   I'm very new to Telerik and still learning A LOT about jquery.   That being said... I wasn't exactly sure how to save the dojo changes for you to review.  So, I've just included it here.  To summarize.

The objective is to:

1) Select a row from the grid.   DONE

2) All matching CustomerID's to the selected row should have the Freight set to zero  DONE

3) The Freight for the selected row should be set to the OrderID  DONE

4)  When "Save" button is clicked, all cells that have been edited should be updated.   This is what does not work.   The grid displays the changes correctly.  Clicking "Save" does update the Freight value that was set to the orderID.   However, the other Freights that match the customerID (which were set to zero) are not updated (because the are not set as a changed cell).   

I do not understand how to use the "echo" functionality of dojo to simulate the change at the server, but I do know that the cells that are changed to zero do not show the "edited" demarcation.   Can you help me?

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8"/>
    <title>Kendo UI Snippet</title>
 
 
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
  </head>
  <body>
 
    <div id="grid"></div>
    <script>
      $("#grid").kendoGrid({
        columns: [
          { field: "CustomerID" },
          { field: "OrderId" },
          { field: "Freight" }
        ],
        dataSource: [
          { CustomerID: "1", OrderId: 30, Freight: 10 },
          { CustomerID: "2", OrderId: 30, Freight: 15 },
          { CustomerID: "3", OrderId: 30, Freight: 11  },
          { CustomerID: "1", OrderId: 30, Freight: 16  },
          { CustomerID: "4", OrderId: 33, Freight: 10  },
          { CustomerID: "2", OrderId: 30, Freight: 20  },
          { CustomerID: "2", OrderId: 30, Freight: 14  },
          { CustomerID: "3", OrderId: 30, Freight: 18  },
          { CustomerID: "1", OrderId: 30, Freight: 12  },
        ],
        toolbar: ["save", "cancel"],
        selectable: "multiple, row",
        editable: true,
        batch: true,
        change: onSelectedRow
      });
 
      function onSelectedRow(e){
        var grid = e.sender;
        var items = grid.items();
        var selectedItem = grid.dataItem(grid.select());
 
        for(var i=0; i<items.length; i++){
         if (grid.dataItem(items[i]).CustomerID == selectedItem.CustomerID) {
            $(items[i]).addClass("k-state-selected");
          }
        }
        var cellsToChange = grid.select();
        for (var i = 0; i < cellsToChange.length; i++) {
            var item = grid.dataItem($(cellsToChange[i]).closest("tr"));
            item.Freight = 0;
        }
        selectedItem.set("Freight", selectedItem.OrderId);
        grid.refresh();
      }
    </script>
  </body>
</html>
0
Eyup
Telerik team
answered on 07 May 2019, 01:22 PM
Hello Bill,

Thank you for choosing to use Kendo as your development assistants. In some short time frame, you will get used to the specifics and find it even more convenient and pleasant to use the widgets. We, the Telerik team, are here to help if you come across any small pebbles or big stones in your way.

For the issue at hand, generally, you can modify the dojo sample by changing the script and running the modified version. You will notice how the URL of the page changes and this new URL holds the updated version.

I am sending another dojo sample to demonstrate that the set method works as expected:
https://dojo.telerik.com/ENiBiWIr/5

Could you modify the previous dojo sample (or this one) to demonstrate the issue you are facing and send the updated version back to us? This will allow us to further investigate the case and provide more accurate and precise suggestions.

Regards,
Eyup
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
Bill
Top achievements
Rank 1
answered on 07 May 2019, 02:14 PM

Eyup,

I appreciate you working with me and helping me to become more familiar with the widgets.   I will attempt to edit the dojo as you have requested even though ti is not even close to my original request BUT.... have you read what I said?????   I have no problem with the set function.   It works fine as shown in the simple example I previously posted.   I also have no problem changing multiple values in the grid by looping through and changing their value to zero.   My issue is that 1) I cannot use the set command in the loop because it rebinds the grid and jumps out of the loop.   Using an "edit.cell" approach changes the cells but they are not updated on the save event.   I don't know if my issue is unclear or if it just cant be done.   Either way.... let me see what I can do to the dojo (which doesn't have a grouping value like a 'product group' so that I can somehow tie this to my OP).  I'm getting pretty frustrated here as I have lost a week on this. 

0
Bill
Top achievements
Rank 1
answered on 07 May 2019, 03:40 PM

Hi Eyup,

Please review http://dojo.telerik.com/uqaLeKoy

You can click a row.   The script will then select (highlight) all rows on the current page that start with the same first letter of the selected row product name.   It will then set the Units in stock of all selected/highlighted rows to Zero.  It will then set the Units In Stock of the selected row to equal the ProductID.    Click save.   All looks well!  But, if you refresh the grid, you will see that ONLY the row that had a changed value using the set command is updated (which makes sense since it is the only cell that shows dirty status).   The other changed cells that were set to zero were not marked dirty and hence were not changed.   This is what I have been asking about in my last 3 responses.   Can you help?

0
Bill
Top achievements
Rank 1
answered on 09 May 2019, 07:05 PM
Any update on this?   anybody?  Buehler??  Buehler??
0
Accepted
Eyup
Telerik team
answered on 10 May 2019, 01:12 PM
Hi Bill,

I've modified the sample to make it work as expected:
http://dojo.telerik.com/uqaLeKoy/15

Sorry if this was a rather time sensitive case. I'd like to mention that there is no dedicated response time frame in the forums. If you prefer, we can convert this thread to an official support thread so you will get replies in 24 hours.

Regards,
Eyup
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
Bill
Top achievements
Rank 1
answered on 10 May 2019, 05:10 PM

Hi Eyup,

Works perfect!   I apologize for venting my frustration.   My snarky humor is one of my worst qualities and rarely helps, especially as I am the one in need of help... I'm working on it.   Thank you also for helping me to better understand how to use the dojo.  I anticipate that having a lot of impact for me with future questions.

0
Accepted
Eyup
Telerik team
answered on 13 May 2019, 11:17 AM
Hello Bill,

I'm glad the provided solution has proven helpful.
Feel free to let us know if new questions arise, packed with good portion of humor.

Reading your statement reveals another quality of yours - humbleness. Keep the good spirit.

Regards,
Eyup
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.
Tags
Grid
Asked by
Bill
Top achievements
Rank 1
Answers by
Eyup
Telerik team
Bill
Top achievements
Rank 1
Share this question
or