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

Change grid cell style with inline edit

2 Answers 2449 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Valentin
Top achievements
Rank 1
Veteran
Valentin asked on 22 Dec 2020, 10:21 AM

Hi team,

I'm trying to create a grid (MVC) that displays data from my model, with rows and cells with background color changing depending of boolean values.  

 

1st try : I used ClientTemplate in my grid to add some class to my cell content.

.ClientTemplate("<div class=#:hasErrorDateDebut?'orangeBack':''#>" +
                            "<div class=#:isActive?'greenBack':''#>" +
                                " #=kendo.toString(dateDebut,'dd / MM / yyyy')# " +
                            "</div>" +
                        "</div>")

hasErrorDateDebut and isActive are the booleans I used to determine if i need to color my cell in orange or green. 

.greenBack {
        background-color: var(--light-green);
    }
 
.orangeBack {
    background-color: #ffb459;
}

 

Issue : It only colors the div inside my td cell. Each td has padding that I can't remove (because each cell of the same line needs to have the same size I suppose), and so the paddings aren't colored. I also tried to set negative margin to counter this padding, but it only works to left and right, and not to top and bottom. 

I now understand that I need to set my class/style to the td element, not the content. But I don't know how I can do so inside ClientTemplate. HtmlAttributes add style/class to the td element correctly, but I can't manage to do so with ClientTemplate. 

 

2nd try : I removed my css and didn't change the ClientTemplate, so the cells I need to color has in it's content a element with orangeBack or greenBack class. I then used javascript to search if td has greenBack or orangeBack class in their content, and then colored them. 

$('tr').has('.greenBack').css('background-color', 'var(--light-green)');
$('td').has('.orangeBack').css('background-color', '#ffb459');

 

Inside a document.ready, it added the desired style to the right td (tr for my green background). This worked perfectly, until I added an Edit command.

columns.Command(command =>
        {
            command.Edit().Text(" ").IconClass("k-icon k-i-edit").Visible("hasNotHappened");
        })
.Editable(editable => editable.Mode(GridEditMode.InLine))

 

Issue : When I click on the edit button, and then validate or cancel my changes, my td and tr classes and styles are erased. I don't know why this happens and how I can prevent it ? 

I tried to use a click function to the .k-grid-cancel to apply my styles again, but it doesn't work. 

$("#gridHistoPeriodesRecueil").data("kendoGrid").bind("edit", function (e) {
    e.container.find(".k-grid-cancel").click(function (e) {
        console.log("tyughujlk");
        $('tr').has('.greenBack').css('background-color', 'var(--light-green)');
        $('td').has('.orangeBack').css('background-color', '#ffb459');
    });
});

 

The log is displayed, but I think the grid and so the element with greenBack and orangeBack classes aren't load when the call is done. I tried to use onDataBound event but it isn't fired. Is there a way to apply my styles like this ?

 

3rd try : I tried to use RowTemplate, as it can allow me to set classes and styles directly to the tr and td I want. But I also want to use Edit command inline. Is there a way to declare it easily in a RowTemplate or only to define the columns I need in RowTemplate and not the whole grid ?

 

 

I hope it was clear enough. I tried many things, but everytime there is an issue I didn't manage to solve. If you can help me to make one of this solution works, let me know.

Thank you,

Valentin

 

2 Answers, 1 is accepted

Sort by
0
Valentin
Top achievements
Rank 1
Veteran
answered on 22 Dec 2020, 10:25 AM

Here's my code

 

My whole grid

@(Html.Kendo().Grid(Model)
    .Name("gridHistoPeriodesRecueil")
    .NoRecords("Aucune période de récueil n'a été trouvée.")
    .Columns(columns =>
    {
    columns.Bound(l => l.dateDebut)
        .Title("Date de début")
        .ClientTemplate("<div class=#:hasErrorDateDebut?'orangeBack':''#>" +
                            "<div class=#:isActive?'greenBack':''#>" +
                                " #=kendo.toString(dateDebut,'dd / MM / yyyy')# " +
                            "</div>" +
                        "</div>")
        .HeaderHtmlAttributes(new { style = "text-align:center;"})
        .Filterable(filterable => filterable
            .Extra(false)
            .Messages(m => m.Info("Afficher les lignes dont la date..."))
            .Operators(operators => operators
                .ForDate(dt => dt.Clear()
                    .IsEqualTo("est...")
                    .IsGreaterThanOrEqualTo("est ultérieure à...")
                    .IsLessThanOrEqualTo("est antérieure à...")))
        );
 
    columns.Bound(l => l.dateFin)
        .Title("Date de fin")
        .ClientTemplate("<div class=#:hasErrorDateFin?'orangeBack':''#> " +
                            "#=kendo.toString(dateFin,'dd / MM / yyyy')# " +
                        "</div>")
        .HeaderHtmlAttributes(new { style = "text-align:center;"})
        .Filterable(filterable => filterable
            .Extra(false)
            .Messages(m => m.Info("Afficher les lignes dont la date..."))
            .Operators(operators => operators
                .ForDate(dt => dt.Clear()
                    .IsEqualTo("est...")
                    .IsGreaterThanOrEqualTo("est ultérieure à...")
                    .IsLessThanOrEqualTo("est antérieure à...")))
        );
 
    columns.Template(@<text></text>)
            .Title("États")
            .Width(125)
            .ClientTemplate("# if(hasErrorDateDebut || hasErrorDateFin) {# <div class='k-icon k-i-warning'></div> #} # " +
                            "# if(isActive) {# <div class='k-icon k-i-doughnut'></div> #} # " +
                            "# if(hasHappened) {# <div class='k-icon k-i-clock'></div> #} #")
            .HeaderHtmlAttributes(new { style = "text-align:center;" });
 
        columns.Command(command =>
        {
            command.Edit().Text(" ").IconClass("k-icon k-i-edit").Visible("hasNotHappened");
            command.Custom("cmdAnnuler").Text(" ").Click("cmdAnnuler").IconClass("k-icon k-i-close").Visible("hasNotHappenedAndNotToday");
        })
                .Title("Actions")
                .Width(125)
                .HeaderHtmlAttributes(new { style = "text-align:center" })
                .HtmlAttributes(new { @class = "actions" });
    })
    //.ClientRowTemplate(
    //    "<tr class=#:isActive?'greenBack':''#>" +
    //        "<td class=#:hasErrorDateDebut?'orangeBack':''#>" +
    //            " #=kendo.toString(dateDebut,'dd / MM / yyyy')# " +
    //        "</td>" +
    //     "</tr>"
    //)
    .Events(events => events
            .DataBound("onDataBound")
        )
    .Editable(editable => editable.Mode(GridEditMode.InLine))
    .HtmlAttributes(new { style = "text-align:center" })
    .DataSource(dataSource => dataSource
        .Ajax()
        .Model(model =>
        {
            model.Id(l => l.idPeriodePaie);
        })
        .Update(update => update.Action("EditingInline_Update", "PeriodesRecueil"))
        .PageSize(50))
    .Pageable()
    .Filterable()
    .Scrollable(scrollable => scrollable.Height(400))
)

 

My css

.greenBack {
        background-color: var(--light-green);
    }
 
.orangeBack {
    background-color: #ffb459;
}

 

My JS

$(document).ready(function () {
        $('tr').has('.greenBack').css('background-color', 'var(--light-green)');
        $('td').has('.orangeBack').css('background-color', '#ffb459');
 
        //$("#gridHistoPeriodesRecueil").data("kendoGrid").bind("edit", function (e) {
        //    e.container.find(".k-grid-cancel").click(function (e) {
        //        console.log("tyughujlk");
        //    });
        //});
    });
 
     
 
function onDataBound(e) {
        //var items = e.sender.items();
        //var grid = $("#gridHistoPeriodesRecueil").data("kendoGrid");
        //items.each(function (index) {
        //    var dataItem = grid.dataItem(this);
        //    if (dataItem.isActive) {
        //        this.classList.add("greenBack");
        //    }
        //})
}

 

0
Accepted
Tsvetomir
Telerik team
answered on 24 Dec 2020, 07:37 AM

Hi Valentin,

When a specific class has to be added to a TD element, it is recommended to do so within the DataBound event handler. Even though this would resolve the case when the item is edited or the grid is repainted, the issue with the cancel edit remains.

This is due to the fact that if the cancel button is clicked, the DataBound event is not triggered. Hence, the cell will be created based on the template of the column but the code for the coloring will not be executed, hence, no color is applied.

In this case, you should subscribe to the Cancel event of the grid and restore the coloring there:

function onCancel(){
             setTimeout(function(){
                        $('td').has('.orangeBack').css('background-color', '#ffb459');
              });
}

The setTimeout function is required to ensure that the cell has already been rendered in "read" mode.

https://dojo.telerik.com/AlARenAr

I hope you find this helpful.

 

Kind regards,
Tsvetomir
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/.

Tags
Grid
Asked by
Valentin
Top achievements
Rank 1
Veteran
Answers by
Valentin
Top achievements
Rank 1
Veteran
Tsvetomir
Telerik team
Share this question
or