Use switch as cell template in kendo grid

13 Answers 4165 Views
Switch (Mobile)
Vedad
Top achievements
Rank 2
Bronze
Bronze
Veteran
Vedad asked on 25 Oct 2018, 02:29 PM

Hello,

I am trying to add a kendo switch to the kendo grid placed within kendo window.

My use case is following:

I create kendo window as directive in angularjs and then display it on button click. 

I create column template for boolean value with kendo switch.

Grid is rendered at load time and no matter what I do, it displays ordinary checkbox or textbox if i remove type="checkbox".

I tried doing the same on following dojo and I get the same results with other data:

https://dojo.telerik.com/oKeXihIW

Just to mention that on the form that invokes directive I have switch and displays properly.

 

Thank you and regards,

Vedad

Vedad
Top achievements
Rank 2
Bronze
Bronze
Veteran
commented on 26 Oct 2018, 07:29 AM

Hi again, 

after reading forum posts to try to foresee other possible obstacles and workarounds I run onto solution for my question. It can be found on the following dojo:

http://dojo.telerik.com/@Iliana/eYUCi

However, I am still confused why on this particular case it doesn't work while on a few other grids it simply works wit the template and example I shown in original question.

Thanks and best regards,

Vedad

Vedad
Top achievements
Rank 2
Bronze
Bronze
Veteran
commented on 26 Oct 2018, 10:15 AM

And yet again, mentioned dojo works for display, but when you add a new row it simply reverts to the checkbox what is sort of inconsistency.

 

Barry
Top achievements
Rank 1
commented on 11 Feb 2020, 06:51 PM

Hi,

I'm trying to do pretty much the same thing with the asp.net core htmlhelpers, except as part of a ClientRowTemplate.

For example, I'd like to show a list of usernames and corresponding switches to show whether each user is opted in to something. Ideally changing the switch will send a request back to the server to save the change in the bound property in the database.

Thanks in advance for any help!

13 Answers, 1 is accepted

Sort by
0
Accepted
Viktor Tachev
Telerik team
answered on 02 Nov 2018, 01:37 PM
Hi Vedad,

In order to handle the change event of the switch widget I would suggest specifying a handler where the widget is initialized:


function createSwitch(element) {
  element.kendoMobileSwitch({
    onLabel: "YES",
    offLabel: "NO",
    change: onChange
  });
}

In the change handler you can perform the relevant calculations and update the Grid dataItem using the set() method.


function onChange(e) {
  var row = e.sender.element.closest("tr");
  var grid = $("#grid").getKendoGrid();
  var dataItem = grid.dataItem(row);
  var checked = e.checked;
 
  dataItem.set("Discontinued", checked);
 
  // sync data with remote service
  grid.dataSource.sync();
}


Optionally you can save the changes by calling sync().

The dojo below illustrates the approach:



Regards,
Viktor Tachev
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.
Vedad
Top achievements
Rank 2
Bronze
Bronze
Veteran
commented on 02 Nov 2018, 03:14 PM

Hi Viktor,

thanks a lot for the effort and provided dojo. It helped solve the problem (I wasn't aware of ability to access row/data item through e when switch is created this way on grid).

Have a nice weekend!

Regards,

Vedad

0
Viktor Tachev
Telerik team
answered on 29 Oct 2018, 10:55 AM
Hi Vedad,

I have examined the dojo sample and noticed that the Switch widgets were created in the template of the column. Thus, when the column is placed in edit mode the default editor will be used.

Furthermore, when the Switch widgets are shown like this changing them would not affect the underlying field. In order to change the value the cell should be placed in edit mode first. To have the Switch modify the values as expected I would suggest defining a custom editor for the column like shown in the custom editor example

For your convenience I modified the dojo sample to illustrate the approach:


Give it a try and let me know how it works for you.


Regards,
Viktor Tachev
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.
Vedad
Top achievements
Rank 2
Bronze
Bronze
Veteran
commented on 29 Oct 2018, 01:02 PM

Hi Viktor, 

Thank for your response and provided dojo. Reason why I went and tried with template is that we have this implementation within app and it works. It doesn't update underlying field but rather executes function which does a few steps. What confuses me is that when I do what I did in dojo, it doesn't draw the switch at all, and this code is working perfectly fine if it was implemented as template on column within detailed grid.

However, at the moment I have two cases:

1. Display data in grid and provide switches based on response, but when switch is flipped do chained actions (I have to do sequence of actions behind and on different data sets).

2. Other option is one where dojo covers approach and it can be used.

I looked into your dojo and this is the approach I took as well, but run onto some other problems and gave up waiting for the response. Dojo seem to work with only one thing, if you go to the edit mode, then cancel, it reverts back to the checkbox.

Any idea how to fix this revertion to checkbox?

Thanks a lot,

best regards.

0
Viktor Tachev
Telerik team
answered on 30 Oct 2018, 10:52 AM
Hi Vedad,

Indeed the checkbox is shown when the Cancel button is clicked. The reason behind this is that the row is redrawn, however, the dataBound event is not raised since there were no changes. In order to recreate the switch you can handle the Grid cancel event and initialize a switch component like in the dataBound hanlder.



Regards,
Viktor Tachev
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.
Vedad
Top achievements
Rank 2
Bronze
Bronze
Veteran
commented on 30 Oct 2018, 02:48 PM

Hi Viktor, thanks a lot for provided Dojo, looks good and works.

I will let you know after I implement and test it.

Btw. It would be interesting if we can find out why on the other place id renders switch only by use of template and on previous dojo it doesn't. It is interesting option because we can make grid readonly and trigger function call behind without grid editing.

Thanks a lot and best regards,

Vedad

Viktor Tachev
Telerik team
commented on 31 Oct 2018, 01:43 PM

Hi Vedad,

Please take your time to test the behavior and see how it works in a real-world scenario.

I modified the sample based on the dojo from your initial post and the switch widget seems to work as expected. Check it out below and let me know how it behaves on your end.



Regards,
Viktor Tachev
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.
Vedad
Top achievements
Rank 2
Bronze
Bronze
Veteran
commented on 31 Oct 2018, 02:53 PM

Hi Viktor, 

for taking the time to make this example, it makes a sense and it works on window. However it is not what I meant in previous post.

In the other part of the app I have detailed grid where I don't use anything else but column template, and grid renders the column with the switch normally and executes function attached to the configuration. (see attached screenshots). And exactly the same approach seems not to work anywhere else I tried. 

Trick is that I need to execute custom function (just use id of the object in grid where switch is flipped and execute javascript function behind to do calculations and other actions before saving data in two different db tables). 

I put screenshot of table and extracts from schema and column definition in controller in attached file. 

Thanks and regards,
Vedad

0
Vedad
Top achievements
Rank 2
Bronze
Bronze
Veteran
answered on 12 Feb 2020, 08:22 AM

Hi Barry, 

I am not familiar with implementation on asp.net core, but basically, I did exactly what was suggested by Viktor. 

function onChange(e) {
    var checked = e.checked;
    var row = e.sender.element.closest("tr");
    var grid = $('#myGrid').data('kendoGrid');
    var dataItem = grid.dataItem(row);
    if (checked) {
        addItem(dataItem);
     } else {
        removeItem(dataItem);
     }
}

 

Basically, you assign HTML template to the column you want and then on databound event you actually add switch widget to that element. 

Something like:

template: function (item) {
return '<input class="switchInGrid" id="' + item.switch_name + '" type="checkbox"' + (item.checked ? 'checked="checked"' : '') + '/>';
}

and then in databound you create switch to that element (I created function for this).

createSwitch(this.tbody.find(".switchInGrid"));

 

function createSwitch(element) {
element.kendoMobileSwitch({
onLabel: localeService.tr('yes'),
offLabel: localeService.tr('no'),
change: onChange
});
}

0
Barry
Top achievements
Rank 1
answered on 12 Feb 2020, 11:44 PM

Hi Vedad,

Thanks for your reply. That is the solution I ended up with, more or less; simply adding a checkbox in to the template and then calling kendoSwitch from javascript later.

If it helps anyone, here is the razor cshtml excerpt:

@(Html.Kendo().Grid(MyListOfUsers)
.Name("grid")
.Columns(columns =>
{
    columns.Bound(c => c.UserName);
    columns.Bound(c => c.IsInRole);
})
.ClientRowTemplate(
"<tr data-myuserid='#:data.UserId#' role='row'>" +
"<td role='gridcell'>#:data.HankUserName#</td>" +
"<td role='gridcell'>" +  
"<input id='swIsInRole_#:data.UserId#' type='checkbox' value='true' # if(data.IsInRole == true) {# checked #} # />"+
"</td>" +
"</tr>"
))

<script>
    kendo.syncReady(
        function () {
            $("[id^='swIsInRole_']").kendoSwitch({
                change: function (e) {
                    console.log(e.sender.element[0].id);
                }
            });
        }
    );
</script>

Vedad
Top achievements
Rank 2
Bronze
Bronze
Veteran
commented on 13 Feb 2020, 07:15 AM

Hi Barry,

I am glad you solved it. :) 

Good luck

0
Vaibhav
Top achievements
Rank 1
answered on 24 Feb 2021, 09:49 AM
thanks for the article. when you click on Yes or No, that particular row is flickering. Can you tell how we can resolve that?
0
Vaibhav
Top achievements
Rank 1
answered on 24 Feb 2021, 09:50 AM
https://dojo.telerik.com/EheFilEF/10
0
Georgi Denchev
Telerik team
answered on 26 Feb 2021, 08:09 AM

Hello Vaibhav,

Thank you for the provided dojo.

The reason the row is flickering is because the dataSource is being synced automatically when the switch status is changed and the row is re-rendered. You can disable the automatic sync by commenting out/removing the following lines of code:

function onChange(e) {
          var row = e.sender.element.closest("tr");
          var grid = $("#grid").getKendoGrid();
          var dataItem = grid.dataItem(row);
          var checked = e.checked;

          dataItem.set("Discontinued", checked);

          // sync data with remote service
          grid.dataSource.sync();
        }

However in this case you would need to manually call the sync method after you've finished editing the rows. Otherwise the changes won't be saved. You would also have to manually set the dirty flag to true when changing the value of the Discontinued column:

function onChange(e) {
          var row = e.sender.element.closest("tr");
          var grid = $("#grid").getKendoGrid();
          var dataItem = grid.dataItem(row);
          var checked = e.checked;

          dataItem.Discontinued = checked;
          dataItem.dirty = true;
        }

Best Regards,
Georgi Denchev
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/.

0
Vaibhav
Top achievements
Rank 1
answered on 02 Mar 2021, 04:30 PM

Hi, 

In one of my scenario, I am binding my grid like 

@(Html.Kendo().Grid(Model).DataSource(dataSource => dataSource

.Ajax() .Read(r => r.Action("GridBind", "Home"))

 

And in GridBind function in home controller, some error came and we want to log in the user again... from login.microsoftonline.com..

when I write return new ChallengeResult(OpenIdConnectDefaults.AuthenticationScheme).. it is giving cors issue..

I have added below code in start up file

//services.AddCors(options =>
//{
// options.AddPolicy("CorsPolicy", builder => builder.WithOrigins("http://localhost:123")
// .AllowAnyHeader()
// .AllowAnyMethod()
// .AllowCredentials()
// .SetIsOriginAllowed((host) => true));
//});

app.UseCors("CorsPolicy");

 

But it is not redirecting to the login.microsoftonline page?

Can you guide me here what I am missing.

I am binding grid using Ajax? Can you tell me what I can pass in Ajax or How to resolve this issue

 

Thank you, Vaibhav

 

 

 

 

 

 

 

 

 

 

0
Georgi Denchev
Telerik team
answered on 04 Mar 2021, 08:59 AM

Hi Vaibhav,

The DataSource.Ajax.Read method expects the Action to return a Json result with the applied request parameters:

public ActionResult GridBind([DataSourceRequest] DataSourceRequest request) {
    var myData = GetDataFromDb();
    return Json(myData.ToDataSourceResult(request));
}

More information on Ajax binding can be found in the following article: Ajax Binding.

CORS errors are usually related to the application configuration itself rather than Kendo. You can read up more on the topic here.

Best Regards,
Georgi Denchev
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/.

0
Vaibhav
Top achievements
Rank 1
answered on 20 Apr 2021, 02:41 PM

Hi, I am using kendoMobileSwitch to create a toggle button in a grid. we are using below library with version:

jQuery: 3.4.1

kendo-ui: 2019.1.115

 

Now, we are updating kendo-ui to 2020.2.617 and jQuery to 3.5.1. After updation kendoMobileSwitch is not working. 

Can you please suggest, how we can resolve this issue.

0
Georgi Denchev
Telerik team
answered on 22 Apr 2021, 09:57 AM

Hi, Vaibhav,

Could you please provide a small dojo sample where the faulty behavior can be observed so I can debug it locally?

I should be able to provide you with a more appropriate response after that.

I'll be looking forward to your reply.

Best Regards,
Georgi Denchev
Progress Telerik

Тhe web is about to get a bit better! 

The Progress Hack-For-Good Challenge has started. Learn how to enter and make the web a worthier place: https://progress-worthyweb.devpost.com.

0
Vaibhav
Top achievements
Rank 1
answered on 22 Apr 2021, 01:09 PM

There was some css class name changes, with the latest version and I identified that and corrected it.

 

Thanks

Tags
Switch (Mobile)
Asked by
Vedad
Top achievements
Rank 2
Bronze
Bronze
Veteran
Answers by
Viktor Tachev
Telerik team
Vedad
Top achievements
Rank 2
Bronze
Bronze
Veteran
Barry
Top achievements
Rank 1
Vaibhav
Top achievements
Rank 1
Georgi Denchev
Telerik team
Share this question
or