We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

Calculate cell value based on values of two cells in Batch Edit Mode

Hi,
 I have the following grid:

                        <div>
                            @(Html.EJ().Grid<SlimHub.Models.QuoteSimulationPlantCost>("QuoteSimulationPlantCostsGrid")
                      .Datasource(ds => ds.Json((IEnumerable<QuoteSimulationPlantCost>)Model.QuoteSimulationPlantCosts.ToList()).UpdateURL("../PlantCostEqUpdate").InsertURL("../PlantCostEqInsert").RemoveURL("../PlantCostEqDelete").BatchURL("../PlantCostBatchUpdate").Adaptor(AdaptorType.RemoteSaveAdaptor))
                      .ShowSummary()
                        .SummaryRow(row =>
                        {
                            row.Title("Totale").SummaryColumns(col => { col.SummaryType(SummaryType.Sum).Format("{0:C}").DisplayColumn("TotalPrice").DataMember("TotalPrice").Add(); }).Add();
                        })
                      .EditSettings(edit =>
                      {
                          edit.AllowAdding().AllowDeleting().AllowEditing().EditMode(EditMode.Batch);
                      })
                      .Locale("it-IT")
                      .ToolbarSettings(toolbar =>
                      {
                          toolbar.ShowToolbar().ToolbarItems(items =>
                          {
                              items.AddTool(ToolBarItems.Add);
                              items.AddTool(ToolBarItems.Edit);
                              items.AddTool(ToolBarItems.Delete);
                              items.AddTool(ToolBarItems.Update);
                              items.AddTool(ToolBarItems.Cancel);
                          }).CustomToolbarItems(
                              new List<object>() {
                                  //new Syncfusion.JavaScript.Models.CustomToolbarItem() {TemplateID = "#Details"},
                                  new Syncfusion.JavaScript.Models.CustomToolbarItem() {TemplateID = "#Details"}});
                      })
                      .AllowResizing()
                      .AllowTextWrap(true)
                      .Columns(col =>
                      {
                          col.Field("PlantCostId").HeaderText("ID").HeaderTextAlign(TextAlign.Center).IsPrimaryKey(true).TextAlign(TextAlign.Right).Width(40).Visible(false).Add();
                          col.Field("QuoteSimId").HeaderText("ID Simulazione").HeaderTextAlign(TextAlign.Center).DefaultValue(Model.QuoteSimId).Width(100).Visible(false).Add();
                          //col.Field("EquipmentId").HeaderText("Attrezzatura").ForeignKeyField("EquipmentId").ForeignKeyValue("EquipmentDesc").DataSource((IEnumerable<object>)ViewBag.Equipments).HeaderTextAlign(TextAlign.Center).Width(80).Add();
                          col.Field("EquipmentId").HeaderText("Attrezzatura").ForeignKeyField("EquipmentId").ForeignKeyValue("EquipmentDesc").DataSource((IEnumerable<object>)ViewBag.Equipments).HeaderTextAlign(TextAlign.Center).Width(80).Add();
                          col.Field("Quantity").HeaderText("Quantità").HeaderTextAlign(TextAlign.Center).TextAlign(TextAlign.Right).Format("{0:n1}").EditType(EditingType.Numeric).NumericEditOptions(new Syncfusion.JavaScript.Models.EditorProperties() { DecimalPlaces = 2, MaxValue = 99999999.99, Locale = "it-IT", MinValue = 0 }).Width(30).Add();
                          col.Field("UnitPrice").HeaderText("Prezzo Unitario").HeaderTextAlign(TextAlign.Center).TextAlign(TextAlign.Right).Format("{0:c2}").EditType(EditingType.Numeric).NumericEditOptions(new Syncfusion.JavaScript.Models.EditorProperties() { DecimalPlaces = 2, MaxValue = 99999999.99, Locale = "it-IT", MinValue = 0 }).Width(30).Add();
                          col.Field("TotalPrice").HeaderText("Prezzo Totale").HeaderTextAlign(TextAlign.Center).TextAlign(TextAlign.Right).Format("{0:c2}").AllowEditing(false).Width(30).Add();
                          col.Field("Annotations").HeaderText("Note").HeaderTextAlign(TextAlign.Center).Width(80).Add();
                      })
                      .ClientSideEvents(eve =>
                      {
                          eve.ActionComplete("PlantComplete");
                          eve.Create("PlantGridCreate");
                          eve.ToolbarClick("PlantToolBarClick");
                          eve.CellEdit("CellEdit");
                          eve.CellSave("CellSave");
                          eve.QueryCellInfo("CalculateTotalPrice");
                      })
                            )
                        </div>

When I change the Quantity field or the UnitPrice field, I want the TotalePrice field to show the total price.

I use the CellSave evento for doing that.

PROBLEM 1:

when I change either the Quantity field or the UnitPrice field, I'm not able to see the new field value for the two fields (I am in batch edit mode).

Example:

    function CellSave(args){
        debugger;
        this.model.columns[2].dataSource = @Html.Raw(Json.Encode((IEnumerable<object>)ViewBag.Equipments));//EquipmentId column

        var gridObj = $("#QuoteSimulationPlantCostsGrid").data("ejGrid");
        var index = gridObj.selectedRowsIndexes;

        if (args.columnName == "Quantity") {
            var newQuantity = args.value, format;// getting the new value
            var unitPrice = gridObj.getSelectedRecords()[0].UnitPrice;
            gridObj.setCellValue(index, "TotalPrice", newQuantity*unitPrice);
        }
        if (args.columnName == "UnitPrice") {
            var newUnitPrice = args.value, format;// getting the new value
            var quantity = gridObj.getSelectedRecords()[0].Quantity;
            gridObj.setCellValue(index, "TotalPrice", quantity*newUnitPrice);
        }

        updatePlantTotals();
        updateTotals();
    }

When I access the CellSave function the second time (the first time is called after changing Quantity field), the selected line of code retreives the original quantity value and not the new edited value. How ca I solve this problem?

PROBLEM 2:

I want the TotalPrice field to be not editable. But if I don't allow editing (as highlighted), I can't change programmatically the value. How can I set the value of a disabled field?

Thanks.

7 Replies

TS Thavasianand Sankaranarayanan Syncfusion Team March 27, 2017 03:36 AM UTC

Hi Claudio, 

Thanks for contacting Syncfusion support. 

Query: Change the value of “TotalPrice” field while changing the “Quantity” or the “UnitPrice” field. 

We have analyzed your query and we suspect that you wants to change the value of column, which is not editable.  

We can achieve your requirement using the setCellText() method and cellSave event of ejGrid control. In our attached sample we have changed the “Freight” column value, which is not editable while changing the “EmployeeId” column value.  

Refer the below code example. 


@(Html.EJ().Grid<object>("FlatGrid") 
        .Datasource((IEnumerable<object>)ViewBag.datasource) 
        .ClientSideEvents(ce=> { ce.CellSave("cellSave"); }) 
        .AllowPaging()    /*Paging Enabled*/ 
        .EditSettings(edit => { edit.AllowAdding().AllowDeleting().AllowEditing().EditMode(EditMode.Batch); }) 
        .ToolbarSettings(toolbar => 
        { 
          ------------- 
        }) 
        .Columns(col => 
        { 
            col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).TextAlign(TextAlign.Right).Width(75).Add(); 
 
           col.Field("EmployeeID").HeaderText("Employee ID").TextAlign(TextAlign.Right).Width(75).Add(); 
            col.Field("Freight").HeaderText("Freight").AllowEditing(false).TextAlign(TextAlign.Right).Width(75).Format("{0:C}").Add(); 
             
 
 
       })) 
</div> 
<script type="text/javascript"> 
    function cellSave(args) { 
   
        var gridObj = $("#FlatGrid").data("ejGrid"); 
        var rowIndex = gridObj.selectedRowsIndexes; 
 
        if (args.columnName == "EmployeeID") { // after the change the employeeid column value 
             
            var employeeID = args.value;// getting the new value in employeeid column 
 
            var cellIndex = 2; // Freight column's cellIndex 
 
            gridObj.setCellText(rowIndex, cellIndex, employeeID * 5); 
        } 
         
    } 
     
</script> 


We have prepared a sample and it can be downloadable from the below location. 


Refer the help documentation. 



Regards, 
Thavasianand S. 



CR CLAUDIO RICCARDI March 27, 2017 03:01 PM UTC

Hi,

I have applied your suggestion, but the problem persists.

When setCellText is called, the server Update method is triggered, that is Batch mode seems not to work.

from official documentation 

setCellText()

Used to update a particular cell value.

NOTE

It will work only for Local Data.This method applicable for all editMode’s except batch edit mode.


but I want to work in Batch Mode...


TS Thavasianand Sankaranarayanan Syncfusion Team March 28, 2017 05:21 PM UTC

Hi Claudio, 
 
Sorry for the inconvenience cause. 
 
We have analyzed your query and we suggest you to enable the allowEditing property while set the value for disabled column, then you can disable the allowEditing for the field. 
 
In the attached sample change the EmployeeID column value then in the cellSave event we can enable the allowEditing for the field Freight then set the value using the setCellValue() method, then disable the allowEditing for that field.  
 
Refer the below code example.  
 
 
@(Html.EJ().Grid<object>("FlatGrid") 
 
.ClientSideEvents(ce=> { ce.CellSave("cellSave"); }) 
 
------------------- 
 
<script type="text/javascript"> 
    function cellSave(args) { 
       
        var gridObj = $("#FlatGrid").data("ejGrid"); 
        var rowIndex = gridObj.selectedRowsIndexes; 
 
        if (args.columnName == "EmployeeID") { 
            debugger 
            var employeeID = args.value;// getting the new value 
            var cellIndex = 4; // Freight column's cellIndex 
            gridObj.model.columns[4]['allowEditing'] = true; // 4 denotes the freight column’s index, enable the allowEditing for the disabled column 
 
            gridObj.setCellValue(rowIndex, "Freight", employeeID * 5); 
 
            gridObj.model.columns[4]['allowEditing'] = false; // 4 denotes the freight column’s index, enable the allowEditing for the disabled column 
        } 
 
    } 
 
</script> 
 
 
We have prepared a sample and it can be downloadable from the below location. 
 
 
Regards, 
Thavasianand S. 



BF Bruno Figueiredo January 31, 2018 02:38 PM UTC

Hi,

Is there a way to do this but in Inline edit ?
I would like to have Quantity and Price columns editable and Total column not editable. And in edit mode, while i change the Quantity or Price, the Total column is displaying the calculated value, live.

In my case, the only difference from this example is the edit mode.
In Inline edit mode, the CellSave event does not get fired.

Thanks,
Bruno Figueiredo


BM Balasubramanian Masilamani Syncfusion Team February 1, 2018 12:20 PM UTC

Hi Bruno,

 

 

We have analyzed your query and we found that you are using inline editMode in grid. Since CellSave event will works only in batch edit mode so we suggest you to use EndEdit event for Inline edit mode.

 

 

Please refer the code sample:

@(Html.EJ().Grid<object>("FlatGrid") 

 

.ClientSideEvents(eve=>eve.EndEdit("endEdit")) 

------------------- 

 

<script type="text/javascript">

    function endEdit(args) {

        var gridObj = $("#FlatGrid").data("ejGrid");

        var rowIndex = gridObj.selectedRowsIndexes;

        var employeeID = args.data.EmployeeID;// getting the new value

        var cellIndex = 4; // Freight column's cellIndex

        gridObj.setCellText(rowIndex, cellIndex, employeeID * 5);

 

    }

 

</script>

 

Please find the documentation link

https://help.syncfusion.com/api/js/ejgrid#events:endedit

 

 

Please let us know if you need any further assistance.

 

Regards,

Balasubramanian Masilamani

 

 



BF Bruno Figueiredo February 1, 2018 04:17 PM UTC

Well, that works but is not live as I wanted it to be (maybe live is not the right word, but I wanted instant changes as I change the fields)

I grabbed the Thor hammer and did this to replicate this behaviour:

 $(document).on('change', "#FlatGridinlineQuantity", function () {
            calcTotal();
        });
        $(document).on('change', "#FlatGridinlineUnitPrice", function () {
            calcTotal();
        });

function calcTotal(){  get values from   $("##FlatGridinlineUnitPrice").val() and do some math }



TS Thavasianand Sankaranarayanan Syncfusion Team February 2, 2018 10:33 AM UTC

Hi Bruno, 

Thanks for contacting Syncfusion support. 

We have analyzed your query and we suspect that you want to calculate two columns then result will be displayed in third column of ejGrid. We have expression column in ejGrid control for doing calculation in columns and also it is known as a template column.  

By binding the keyup event for the Freight and EmployeeID column in the actionComplete event of ejGrid control. Then we able to do calculation while entering or typing the values in Freight and EmployeeID column’s input text box.  

For an example, we have calculated with the “Freight”, “EmployeeID” column and the result will be generated in “CalculatedColumn” 

Refer the below code example. 


@(Html.EJ().Grid<object>("FlatGrid") 
         
        .AllowPaging() 
        .ClientSideEvents(cevent => cevent.ActionComplete("complete")) 
     
         ---          
 
        .Columns(col => 
        { 
            col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width(75).Add(); 
            col.Field("Freight").HeaderText("Freight").Width(100).Add(); 
            col.Field("EmployeeID").HeaderText("Employee ID").Width(90).Add(); 
            col.HeaderText("Calculated Column").Template("<span id='CalcCol'>{{:EmployeeID * Freight }}</span>").Width(90).Add(); 
        })) 
</div> 
<script type="text/javascript"> 
    function complete(args) { 
        if (args.requestType == "beginedit" || args.requestType == "add") { 
            $("#" + this._id + "EmployeeID").keyup(function (event) { 
                Valuechange(); 
            }); 
            $("#" + this._id + "Freight").keyup(function (event) { 
                Valuechange(); 
            }); 
        } 
    } 
    function Valuechange(args) { 
 
       var employeeID = $("#FlatGrid" + "EmployeeID").val(); 
       var freight = $("#FlatGrid" + "Freight").val();         
       $("#CalcCol")[0].innerHTML = parseFloat(employeeID) * parseFloat(freight); 
    } 
</script> 


We have prepared a sample and it can be downloadable from the below location. 


Refer the help documentation. 



Regards, 
Thavasianand S.  


Loader.
Live Chat Icon For mobile
Up arrow icon