How can I have a checkbox column in a grid without having to click on the checkbox twice to edit?

5 Answers 1446 Views
Checkbox Grid
Mathew
Top achievements
Rank 1
Mathew asked on 16 Mar 2022, 05:11 PM | edited on 16 Mar 2022, 05:11 PM

I want to display a boolean value in an ASP.NET Core Kendo grid column. However, I need it to display a checkbox in the column because I don't want to show the users the raw data. So, I put in a custom client template because it's not an option to have booleans display a checkbox despite that seeming like an option that should be available by default. However, this grid is supposed to be editable inline using the default CRUD operations and you have to click on the cells to bring up the editor.

The default editor for a boolean column is a checkbox. So, the users click on a checkbox to bring up a different checkbox and it looks like it just didn't work. If I make the initial checkbox greyed out, it looks like they can't edit it. So, no matter what I do, I can't make a column a checkbox and use the default editor without a bunch of ugly design issues which is ridiculous.

Am I just missing something? Is there a better way than resorting to doing scripting with Javascript and setting the column to uneditable?

5 Answers, 1 is accepted

Sort by
2
Accepted
Aleksandar
Telerik team
answered on 21 Mar 2022, 06:22 AM

Hi Mathew,

The ClientTemplate is used to customize the content that will be rendered by the Grid for a column. The Grid has no knowledge on what that content might be set by the developer so it is not handling the updates. You have not mentioned the editing mode of the Grid used, so I will assume you have InCell editing. To achieve the desired behavior you need to take the following steps:

  • Disable editing for the column. This way the second checkbox editor will not be generated.
  • Handle the change of the checkbox state in the client template and update the underlying model.

Column definition

columns.Bound(p => p.Discontinued)
            .ClientTemplate("#=dirtyField(data,'Discontinued')#<input type='checkbox' #= Discontinued ? checked='checked' : '' # class='chkbx k-checkbox k-checkbox-md k-rounded-md' />")
            .Editable("returnFalse")
            .Width(100);

scripts

 function returnFalse(){
        return false
    }

    $("#grid .k-grid-content").on("change", "input.chkbx", function(e) {
        var grid = $("#grid").data("kendoGrid"),
            dataItem = grid.dataItem($(e.target).closest("tr"));

        dataItem.set("Discontinued", this.checked);
      });

    function dirtyField(data, fieldName){
        var hasClass = $("[data-uid=" + data.uid + "]").find(".k-dirty-cell").length < 1;
        if(data.dirty && data.dirtyFields[fieldName] && hasClass){
          return "<span class='k-dirty'></span>"
        }
        else{
          return "";
        }
    }

Here is a sample REPL where you can see a runnable example of the above suggestion.

Regards,
Aleksandar
Progress Telerik

Virtual Classroom, the free self-paced technical training that gets you up to speed with Telerik and Kendo UI products quickly just got a fresh new look + new and improved content including a brand new Blazor course! Check it out at https://learn.telerik.com/.

Mathew
Top achievements
Rank 1
commented on 21 Mar 2022, 01:18 PM

I appreciate it. Thank you.
0
Maksim
Top achievements
Rank 1
Iron
answered on 03 Jun 2023, 07:30 AM | edited on 03 Jun 2023, 07:59 AM
Hi!

This example does not work correctly.

1. No Dirty status on the changed checkbox.

2. Changed status is not written to EF. This can be seen in my example, as well as in the example of https://netcorerepl.telerik.com/mwYHwvEg18Y9oEgo52. If you click on Save, the status will disappear .

My opinion is that this question should work correctly out of the box without additional coding. If this is not available, then there should be an applicable sample code.

I've seen many examples of Checkbox in Grid, but I haven't seen one that works correctly. Is it possible to make an example where EF, Dirty works, no double click required and the checkbox always looks like a checkbox (.NET7)?

Best regards
Maksim


Aleksandar
Telerik team
commented on 07 Jun 2023, 11:09 AM

Hi Maksim,

I guess I'm missing something - when running the REPL example linked above and editing a checkbox the dirty flag is set and dataItems are submitted to the endpoint, as you can see in this screencast.

An alternative approach, demonstrating the use of the MVVM pattern can be found in this REPL:

https://netcorerepl.telerik.com/mHEUaVFv042EaRMv33

@(Html.Kendo().Grid<Kendo.Mvc.Examples.Models.ProductViewModel>()
    .Name("Grid")
    .Columns(columns => {
        columns.Bound(p => p.ProductName);
        columns.Bound(p => p.UnitPrice).Width(140);
        columns.Bound(p => p.UnitsInStock).Width(140);
        columns.Bound(p => p.Discontinued).Editable("returnFalse")
        .ClientTemplate(
            Html.Kendo().CheckBox()
                .Name("cbx#=ProductID#")
                .HtmlAttributes(new{data_bind="value: Discontinued"})
                .ToClientTemplate().Value
            ).Width(100);
        columns.Command(command => command.Destroy()).Width(150);
    })
    .Events(ev=>ev.DataBound("onDataBound"))
    .ToolBar(toolbar => {
        toolbar.Create();
        toolbar.Save();
    })
    .Editable(editable => editable.Mode(GridEditMode.InCell))
    .Pageable()
    .Navigatable()
    .Sortable()
    .Scrollable()
    .Events(events => events.Sort("onSort"))
    .DataSource(dataSource => dataSource
        .Ajax()
        .Batch(true)
        .PageSize(20)
        .ServerOperation(false)
        .Events(events => events.Error("error_handler"))
        .Model(model => model.Id(p => p.ProductID))
        .Create("Editing_Create", "Grid")
        .Read("Editing_Read", "Grid")
        .Update("Editing_Update", "Grid")
        .Destroy("Editing_Destroy", "Grid")
    )
)
<script type="text/javascript">
        function returnFalse(){
                return false
            }
        function onDataBound(e) {
            var grid = this;
            grid.table.find("tr").each(function () {
                var dataItem = grid.dataItem(this);

                $(this).find('script').each(function () {
                    eval($(this).html());
                });

                kendo.bind($(this), dataItem);
            });
        }
        function error_handler(e) {
            if (e.errors) {
                var message = "Errors:\n";
                $.each(e.errors, function (key, value) {
                    if ('errors' in value) {
                        $.each(value.errors, function() {
                            message += this + "\n";
                        });
                    }
                });
                alert(message);
            }
        }

        // Prevent sorting when new record without Product Name is added
        function onSort(e) {
            var gridData = e.sender.dataSource.data()
            gridData.forEach(function (element) {
                if (!element.ProductName) {
                    e.preventDefault()
                }
            });
        }
    </script>

Once again the behavior is the same - when checking/unchecking a checkbox the dirty flag is shown and data is submitted.

0
Maksim
Top achievements
Rank 1
Iron
answered on 08 Jun 2023, 05:33 AM

Hi, Aleksandar!

Thank you very much for your willingness to help and the new version!

You made an example that works much better (EF, Dirty, no double click, checkbox always looks like a checkbox).

But there are problems.

1. After clicking on the CheckBox, the data is refreshed, and the focus goes to the first column of the first row. If the click was on the wide form on the right side through scrolling, then the whole screen shifts to the left. You can easily see if you narrow the example window.

2. I have 29 rows and 20 columns in my form. After clicking on the checkbox, the client thinks for about 1.5 seconds. All other controls work instantly. This is very long if you put down 5-10 checkboxes. And of course, the form running up and to the left (point 1).

But what is in the example already gives hope that it will be possible to get a working and recommended example by TELERIK.

Regards

Maksim

Maksim
Top achievements
Rank 1
Iron
commented on 08 Jun 2023, 05:40 AM

.... slowdown when clicking on the checkbox ~ 0.2 seconds is also visible in your example ....
0
Aleksandar
Telerik team
answered on 12 Jun 2023, 11:18 AM

Hi Maksim,

1) If you desire to preserve the focus I can suggest reviewing this knowledgebase article and implementing the suggested approach:

2) The behavior would be expected - a client-side template is being used and the template contains an editor(a CheckBox component in the current example). This way, every time the state of the checkbox is changed essentially the entire grid is re-rendered and the CheckBox components are reinitialized. In this scenario the use of the MVVM pattern is essentially doing the same as in the initial suggestion - the set method is called. Note that when the default behavior is used this is not the case - the cell enters edit mode - the state is updated, but the Grid keeps track of the changes and only when the Save Changes button is pressed the entire Grid is re-rendered. You can verify this in these two REPLs:

The observed behavior and performance implications are documented in the Performance Tips section of the documentation.

Regards,
Aleksandar
Progress Telerik

As of R2 2023, the default icon type will be SVG instead of Font. See this blogpost for more information.
0
Maksim
Top achievements
Rank 1
Iron
answered on 10 Nov 2023, 07:19 AM | edited on 10 Nov 2023, 08:47 AM

 

Hi, Aleksandar!

I have applied this solution to about 50 grids in the last 5 months and it works fine. There is a slight slowdown, but it is not critical. The solution is applicable in practice. In the future it is possible that TELERIK will support the required functionality out of the box and it will work faster. The entire palette of customization and depth of features can be left, just add .Archaic mode, and it will cover 98 percent of customer needs.

Best regards
Maksim

 

Mihaela
Telerik team
commented on 14 Nov 2023, 10:05 PM

Hi Maksim,

Thank you for the update.

If you would like to request such feature to be included out of the box for the Grid, I can suggest submitting a request in our Feedback Portal. The feature requests logged in the portal are reviewed and evaluated by the Telerik UI for ASP.NET Core team. Based on the community's interest, they are planned for implementation in subsequent releases.

Maksim
Top achievements
Rank 1
Iron
commented on 15 Nov 2023, 08:36 AM

Hi Mihaela,

I don't have time to do that too. But if there are questions on the forum, then they can probably go to the developers for discussion automatically.

Best regards
Maksim


Tags
Checkbox Grid
Asked by
Mathew
Top achievements
Rank 1
Answers by
Aleksandar
Telerik team
Maksim
Top achievements
Rank 1
Iron
Share this question
or