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

Grid computed columns, phone mode, etc..

Hello!

I have few questions:

- can you provide some best practice for creating computed fields and row totals (like order_detail.price * order_detail.quantity * order detail.tax)? 
I have tried with "querycellinfo" and it's working for first render and when refreshContent() is called, but I'm using grid in batch edit mode so I need line item totals to be recalculated on moving around cells.. For that requirement I have tried with "cellSaved" event and it's working but it seems like overhead to me, perhaps there is a easier way..

- connected to previous question: are there some specifics for unbound columns to be set-up, I was reading about command property but it seems that it's working without setting up (despite occasionally  I do have some messed up screen rendering showing some checkboxes on the screen and grid searchbox at the top over existing elements - don't know what's causing that - I have provided screenshot in attachment - render1.jpg)..

- is it possible to turn on phone mode render at resolution of i.e. 400px (currently it is 321px), most of modern phones have resolution more then 321px and grid still doesn't look nice at that small resolution so phone mode would be ideal..

- is there a way to manually refresh (custom) summaries? They are refreshed when refreshContent() is called but in batch edit mode if you refresh the grid you exit editing mode.. (I'm using "AddEdit" type of screen so I believe I cannot use grid "save" method)..

Rendering code of grid:


myapp.AddEditPovratiSF.Povrati_stavke_grid_render = function (element, contentItem) {
    var itemTemplate = $("<div></div>").attr('id', 'Povrati_stavke_grid')
    itemTemplate.appendTo($(element));
    //Have a global flag for add
    window.isAdd = false;

    contentItem.value.oncollectionchange = function () {
    
        contentItem.screen.Zapisa = lsWire.getDataItemCount(contentItem.screen.Povrati_stavke, false); 

        /*Important - Used to prevent the oncollectionchange
           action on adding new record to vs collection*/
        if (window.isAdd) return;

        if (itemTemplate.hasClass('e-grid')) {
            itemTemplate.ejGrid('destroy');
        }

        //Rendering the Grid Control
        itemTemplate.ejGrid(
            {
                dataSource: contentItem.value.data,
                allowSearching: true,
                //allowPaging: true,
                //pageSettings: { pageSize: 5 }, //Setting the pageSize as 10 and hence first 10 records will be requested
                enableResponsiveRow: true,
                isResponsive: true,
                //minWidth: 450,
                allowTextWrap: true,
                allowKeyboardNavigation: true,
                allowColumnSelector: true,
                enableAutoSaveOnSelectionChange: false,
                locale: "hr-HR",
                //allowScrolling: true,
                //scrollSettings: { width: "auto", height: 280 },
                showColumnChooser: true,
                showSummary: true,

                editSettings: {
                    allowEditing: true,
                    allowAdding: true,
                    allowDeleting: true,
                    allowEditOnDblClick: true,
                    editMode: ej.Grid.EditMode.Batch,
                    showDeleteConfirmDialog: false, 
                    showConfirmDialog: false

                },

                toolbarSettings: {
                    showToolbar: true,
                    toolbarItems: [
                        ej.Grid.ToolBarItems.Add,
                        ej.Grid.ToolBarItems.Edit,
                        ej.Grid.ToolBarItems.Delete,
                        //ej.Grid.ToolBarItems.Update,
                        ej.Grid.ToolBarItems.Cancel,
                        ej.Grid.ToolBarItems.Search
                    ],
                },

                columns: [
                         { field: "Id", isPrimaryKey: true, headerText: "ID", textAlign: ej.TextAlign.Right, width: 60, allowEditing: false, visible: false },
                         { field: "Sifra_artikla", headerText: 'Šifra', width: 50, allowEditing: false, priority: 1 },
                         { field: "Artikal.Naziv", headerText: "Artikal", width: 100, allowEditing: false, priority: 1 },
                         { field: "Cijena", headerText: 'Cijena', format: "{0:C2}", textAlign: ej.TextAlign.Right, width: 50, priority: 1, allowEditing: false },
                         { field: "PDV", headerText: 'PDV', format: "{0:N2}", textAlign: ej.TextAlign.Right, width: 50, editParams: { decimalPlaces: 2 }, priority: 1, allowEditing: false },
                         { field: "Kolicina", headerText: 'Količina', format: "{0:N2}", textAlign: ej.TextAlign.Right, width: 50, priority: 1 },
                         { field: "Kolicina_dodatno", headerText: 'Dod. količina', format: "{0:N2}", textAlign: ej.TextAlign.Right, width: 50, priority: 1 },
                         { headerText: 'Tot. količ', format: "{0:N2}", textAlign: ej.TextAlign.Right, width: 50, priority: 1, allowEditing: false, isUnBound: true, field: "Totkol" },
                         { headerText: 'Tot. stavk', format: "{0:C2}", textAlign: ej.TextAlign.Right, width: 50, priority: 1, allowEditing: false, isUnBound: true, field: "Total" }
                ],

                summaryRows: [
                    {   title: "Total povrata", summaryColumns: [
                          {   summaryType: ej.Grid.SummaryType.Custom, customSummaryValue: getTotalKolp,
                              displayColumn: "Totkol", dataMember: "Totkol", format: "{0:n2}" },
                          {   summaryType: ej.Grid.SummaryType.Custom, customSummaryValue: getTotalp,
                              displayColumn: "Total", dataMember: "Total", format: "{0:c2}" },
                          {   summaryType: ej.Grid.SummaryType.Count, prefix: "Zapisa:  ",
                              displayColumn: "Artikal.Naziv", dataMember: "Id" }
                        ]
                    }
                ],

                beforeBatchAdd: function (args) {
                    window.isAdd = true;
                },

                queryCellInfo: function (args) {
                    var a = args;
                    if (args.column.field == "Totkol") {
                        var totkol = (parseFloat(args.data.Kolicina) + parseFloat(args.data.Kolicina_dodatno)).toFixed(2);
                        args.cell.innerText = totkol.toString();
                    }
                    if (args.column.field == "Total") {
                        var totkol = (parseFloat(args.data.Kolicina) + parseFloat(args.data.Kolicina_dodatno)).toFixed(2);
                        var total = (parseFloat(totkol) * parseFloat(args.data.Cijena) * (1 + parseFloat(args.data.PDV))).toFixed(2);
                        args.cell.innerText = total.toString();
                    }
                },

                cellSave: function (args) {
                    var a = args;
                    if (args.columnName == "Kolicina") {
                        var index = this.getIndexByRow(args.cell.parent());
                        var totkol = parseFloat(args.value) + parseFloat(args.rowData.Kolicina_dodatno);
                        var total = parseFloat(totkol) * parseFloat(args.rowData.Cijena) * (1 + parseFloat(args.rowData.PDV));
                        this.setCellValue(index, "Totkol", totkol.toFixed(2));
                        this.setCellValue(index, "Total", total.toFixed(2));
                    }
                    if (args.columnName == "Kolicina_dodatno") {
                        var index = this.getIndexByRow(args.cell.parent());
                        var totkol = parseFloat(args.rowData.Kolicina) + parseFloat(args.value);
                        var total = parseFloat(totkol) * parseFloat(args.rowData.Cijena) * (1 + parseFloat(args.rowData.PDV));
                        this.setCellValue(index, "Totkol", totkol.toFixed(2));
                        this.setCellValue(index, "Total", total.toFixed(2));
                        //refreshGrd();
                    }
                },

                rowSelected: function (args) {
                    selectedData = args.data;
                },

                toolbarClick: function (args) {
                    switch (args.itemName) {
                        case "Add":
                            args.cancel = true;
                            myapp.showScreen("AddEditPovrati_stavke", null, {
                                beforeShown: function (addScreen) {
                                    var ord = new myapp.Povrat_stavka();
                                    addScreen.Povrat_stavka = ord;
                                    ord.setPovrat(contentItem.screen.Povrat);
                                }
                            });
                            break;
                        case "Edit":
                            if (!($.isEmptyObject(selectedData))) {
                                args.cancel = true;
                                myapp.showScreen("AddEditPovrati_stavke", [selectedData]);
                            }
                            break;
                        case "Cancel":
                            contentItem.screen.details.dataWorkspace.ApplicationData.details.discardChanges();
                            break;
                        case "Delete":
                            contentItem.value.selectedItem = this.getSelectedRecords()[0];
                            if (!($.isEmptyObject(contentItem.value.selectedItem)) && !($.isPlainObject(contentItem.value.selectedItem))) {
                                try {
                                    contentItem.value.deleteSelected();
                                }
                                catch (err) {
                                    alert(err);
                                }
                            };
                            break;
                    }
                },                          
            });
    }
}

function getTotalKolp() {
    var gridObj = $("#Povrati_stavke_grid").ejGrid("instance");
    var qt = 0;
    for (var i = 0; i < gridObj.model.dataSource.length; i = i + 1) {
        qt = parseFloat(qt) + parseFloat(gridObj.model.dataSource[i].Kolicina) + parseFloat(gridObj.model.dataSource[i].Kolicina_dodatno);
    }
    return (qt);
}

function getTotalp() {
    var gridObj = $("#Povrati_stavke_grid").ejGrid("instance");
    var qt = 0;
    for (var i = 0; i < gridObj.model.dataSource.length; i = i + 1) {
        var kol = parseFloat(gridObj.model.dataSource[i].Kolicina) + parseFloat(gridObj.model.dataSource[i].Kolicina_dodatno);
        var cij = parseFloat(gridObj.model.dataSource[i].Cijena);
        var pdv = parseFloat(gridObj.model.dataSource[i].PDV);
        var tot = kol * cij * (1 + pdv);
        qt = (parseFloat(qt) + parseFloat(tot)).toFixed(2);
    }
    return (qt);
}

function refreshGrdp() {
    setTimeout(function () {
        $("#Povrati_stavke_grid").ejGrid("refreshContent");
    }, 250);
}



Attachment: render1_5fc5b215.7z

10 Replies

SA Saravanan Arunachalam Syncfusion Team November 17, 2015 01:25 PM UTC

Hi Dr,

Thanks for contacting Syncfusion Support.

Query 1: I have tried with "cellSaved" event and it's working but it seems like overhead to me.

When perform Editing, the changes affected only on the edited cells and the content will be refreshed after the batch save. So, refresh the compute column when edit the cell each time using cellSave event of Grid like as you said.

Query 2: are there some specifics for unbound columns to be set-up.

Please provide the following information regarding your query?

1.       What did you meant the unbound column set-up?

2.       Did you mean recalculate the compute field while editing using command column?

Query 3 & Query 4?

We are validating your requirement, we will get back to you with further information on November 18, 2015.

Regards,

Saravanan A.



DR dr November 17, 2015 03:40 PM UTC

Hello Saravanan A!
Thanks for your response!

- I was wondering if there is something specific when setting unbound column? Does it somehow affect grid rendering? I have read some post on your forums where asker didn't set command property so he had issues with grid rendering, I was curious is this necessity, or is it OK like I was doing in previous post code example?

I'm just trying to find the best way to achieve computed columns and summaries.. is there some event which would allow me to recompute totals, like (perhaps) "endEdit" but for batch mode?

Kivito


SS Seeni Sakthi Kumar Seeni Raj Syncfusion Team November 18, 2015 02:09 PM UTC

Hi Kivitio,

Query #1: I was wondering if there is something specific when setting unbound column? Does it somehow affect grid rendering?

You have given the field for the unbound columns. Usually, the unbound columns are the columns which are not present in the dataSource and for these columns Grid functionalities like grouping, sorting and editing will not be applicable. A column with other controls and the columns doesn’t have value in dataSource, we will specify them as unbound column.

Query #2: I'm just trying to find the best way to achieve computed columns and summaries.

On Bulk save of the Grid, it will automatically recalculate the Summary values. Expression Column functionality of Grid will helps you in achieving the computed columns. Please refer to the following Help Document.
 
http://help.syncfusion.com/js/grid/columns#expression-column

Query #3 & #4:

We are validating your requirement, we will get back to you with further information on November 19, 2015. 

Regards,
Seeni Sakthi Kumar S.


DR dr November 20, 2015 07:44 AM UTC

Hello Seeni!
I was looking expressions column but unfortunately it is not clear how to use it within lightswitch. I have managed to succeed in showing and combining value(s) in expression cell, but I can't do any calculations.. Can you please provide some code example where line items are calculated (like row.data.Price * row.data.Quantity) in expression column..

I was playing with this code:

var templateform = $('<script type="text/x-jsrender" id="test"></script>').html('<div>Value: {{:Kolicina}}</div>'); //it shows quantity (i.e. Value: 10) in expression column

now for calculations it is noted that allowCode setting should be set to true and I tried like this but it does not show any value except "My var:":

$.views.settings.allowCode = true; //can't figure out how to set "allowCode" just for this template from lightswitch and not sure if this works
var templateform = $('<script type="text/x-jsrender" id="test"></script>').html('<div>{{* myvar= 5; }}My var: {{*: myvar}}</div>');  //it just shows "My var:" in expression column

Under columns I have defined:

....,
columns: [ ....,
                 { headerText: 'Total', template: true, templateID: templateform, textAlign: ej.TextAlign.Right, width: 100 },
                ..... ],
....,

Thanks!
Kivito



SA Saravanan Arunachalam Syncfusion Team November 23, 2015 09:17 AM UTC

Hi Kivito,

Query 1: I was looking expressions column but unfortunately it is not clear how to use it within lightswitch.

We can render the template column two ways in LightSwitch Html.

1.       Render the template in the column itself.

We can render the column template in the Grid column itself using template property of Grid column. Please refer to the code example.

columns: [

                      . . .

                   

                        { headerText: "ExpressionCell", width: 75, template: "<span>{{:EmployeeID * Freight}}</span>"}

         ]

                       


2.       Render the template using TemplateID property  

Render the JSRender template for the column using TemplateID property of Grid Column. Please refer to the code example and online documentation link.

[default.html]

<script type='text/jsrender' id='expTemp'>

        <span>{{:EmployeeID * Freight}}</span>

 </script>

columns: [

                 //TemplateID should be id of the JSRender element

                { headerText: "ExpressionCell", width: 75, template: true, templateID: "#expTemp"}

                        ]

                       


http://help.syncfusion.com/js/api/ejgrid#members:columns-templateid

Query 2: Refresh the Custom Summary

We have refreshed the custom Summary using “cellSave” event of Grid and recomputed the expression cell (Template column). Please refer to the code example.

cellSave: function (args) {

                    var calc=0;

                    if (args.columnName == "EmployeeID")

                        calc = args.value + parseFloat(args.rowData.Freight);

                    else if (args.columnName == "Freight") {

                        calc = parseFloat(args.value) + parseFloat(args.rowData.EmployeeID);

                        var extra = parseFloat(args.value) - parseFloat(args.previousValue);

                        //To recompute the template cell

                        args.cell.closest("tr").find(".e-templatecell span")[0].innerHTML = calc.toString();

                        //To Refresh Custom Summary

                        var summary = ($("td.e-summaryrow")[args.cell.index()].innerHTML).replace(/[$,]/g, "")

                        var summaryval = (parseFloat(summary) + extra).toFixed(2);

                        $("td.e-summaryrow")[args.cell.index()].innerHTML = "$" + summaryval;//assigning the innerHTML of the summaryrow with updated value

                    }

                },

               


We have created a sample that you can download from the below link.

http://www.syncfusion.com/downloads/support/forum/121162/ze/F121162-709422308

Regards,

Saravanan A.



SA Saravanan Arunachalam Syncfusion Team November 23, 2015 10:10 AM UTC

Hi Kivito,

Please ignore the previous update.

Query 1: I was looking expressions column but unfortunately it is not clear how to use it within lightswitch.

We can render the template column two ways in LightSwitch Html.

1.       Render the template in the column itself.

We can render the column template in the Grid column itself using template property of Grid column. Please refer to the code example.

columns: [

                      . . .

                   

                        { headerText: "ExpressionCell", width: 75, template: "<span>{{:EmployeeID * Freight}}</span>"}

         ]

                       


2.       Render the template using TemplateID property  

Render the JSRender template for the column using TemplateID property of Grid Column. Please refer to the code example and online documentation link.

[default.html]

<script type='text/jsrender' id='expTemp'>

        <span>{{:EmployeeID * Freight}}</span>

 </script>

columns: [

                 //TemplateID should be id of the JSRender element

                { headerText: "ExpressionCell", width: 75, template: true, templateID: "#expTemp"}

                        ]

                       


http://help.syncfusion.com/js/api/ejgrid#members:columns-templateid

Query 2: Refresh the Custom Summary

We have refreshed the custom Summary using “cellSave” event of Grid and recomputed the expression cell (Template column). Please refer to the code example.

cellSave: function (args) {

                    var calc=0;

                    if (args.columnName == "EmployeeID")

                        calc = args.value + parseFloat(args.rowData.Freight);

                    else if (args.columnName == "Freight") {

                        calc = parseFloat(args.value) + parseFloat(args.rowData.EmployeeID);

                        var extra = parseFloat(args.value) - parseFloat(args.previousValue);

                        //To recompute the template cell

                        args.cell.closest("tr").find(".e-templatecell span")[0].innerHTML = calc.toString();

                        //To Refresh Custom Summary

                        var summary = ($("td.e-summaryrow")[args.cell.index()].innerHTML).replace(/[$,]/g, "")

                        var summaryval = (parseFloat(summary) + extra).toFixed(2);

                        $("td.e-summaryrow")[args.cell.index()].innerHTML = "$" + summaryval;//assigning the innerHTML of the summaryrow with updated value

                    }

                },

               


We have created a sample that you can download from the below link.

http://www.syncfusion.com/downloads/support/forum/121162/ze/F121162913076687

Regards,

Saravanan A.



DR dr November 23, 2015 11:00 AM UTC

Hello Saravanan A.!
Thank you for your response and for example, it was really helpful! 
In addition to your last post, how could I force expression template to add numbers instead of concatenating as strings? If I put "+" sign in expression it will concatenate result ie.:
{ ...., template: "<span>{{: ItemQuantity + ItemReserved}}</span>" }
will produce 10.0020.00..

As for grid in phone mode: 
- can I manually force grid to render in phone mode at resolution more then 321px (ie 400px)?

Thanks again! 
Kivito


SA Saravanan Arunachalam Syncfusion Team November 24, 2015 08:50 AM UTC

Hi Kivito,

Query 1: How could I force expression template to add numbers instead of concatenating as strings?

To add the numbers using template column, the numbers should not be string. If the numbers are string, it will concatenate instead of adding.

We have achieved your requirement using “Jquery helpers” which parses the string to float, adds and then return to the template column. Please refer to the below code example.

<script type='text/jsrender' id='expTemp'>

        {{>~ Adding (EmployeeID, Freight)}}

    </script>

<script type="text/javascript">

       

        $.views.helpers({

            Adding: function (args1, args2) {

                sum = args1 + parseFloat(args2);

                return sum;

            }

        });


    </script>

itemTemplate.ejGrid(

            {

                dataSource: data,

                . . .

                columns: [

                    . . .

                        { headerText: "ExpressionCell", width: 75, template: true, templateID: "#expTemp" }

                

                        ]

                       

            });

    }

 

Query 2 : Can I manually force grid to render in phone mode at resolution more then 321px (ie 400px)?

Yes, you can render the Grid in phone mode at resolution more than 321px through overwriting the media query css in “ejgrid.responsive.css” which is located in following location and refer to the code to overwrite the css.

{programfilesfolder}\Syncfusion\Essential Studio\{Version}\JavaScript\assets-src\css\web\responsive-css\ejgrid.responsive.

/*overwrite from 320px to 400px*/

@media (max-width :400px) {

    .e-grid.e-responsive > [id*='Dlg_wrapper'] {

        width: 130px !important;

    }

/*When greater than the phone mode(changed from 321px to 401px )*/

@media (min-width: 401px) and (max-width:479px) {

    .e-grid .e-table-priority-6,

    .e-grid .e-table-priority-5,

    .e-grid .e-table-priority-4,

    .e-grid .e-table-priority-3,

    .e-grid .e-table-priority-2 {

        display: none !important;

    }

}



Regards,

Saravanan A.



DR dr November 25, 2015 07:43 AM UTC

Hi!
Thanks for answers and examples! Great support!
I'll try to implement this into production app.. 

Kivito


SA Saravanan Arunachalam Syncfusion Team November 26, 2015 06:44 AM UTC

Hi Kivito,

Thanks for your update.          

We are happy that the provided information helped you.

Regards,

Saravanan A.


Loader.
Live Chat Icon For mobile
Up arrow icon