Reload/Refresh Kendo Grid - javascript

I need to reload all the grid (not only the data).
I'm trying with:
$('#GridName').data('kendoGrid').dataSource.read();
$('#GridName').data('kendoGrid').refresh();
but read() reloads only the data and refresh() is not working. When a user clicks on the button, I need to recreate all the table with new columns (I don't know how many columns or what columns, the server process it).
Users can change the columns that they see with a html checkbox. The first time the table charges correctly but if the user change the checkbox value the columns don't change. If deselect an option the column is empty and if the user adds an option, the new column don't appear.
How can I achieve this?

You should destroy and recreate the grid to change the columns.
$.ajax(
{
type: 'GET',
url: yourURL,
dataType: 'json',
success: function (result) {
$('#Grid').data('kendoGrid').destroy();
$('#Grid').empty(); //necessary to remove the old html
$("#grid").kendoGrid({
dataSource: {
data: result,
schema: {
data: "d"
}
}
});
}
});
The result of your ajax should be something like:
var result = { 'd': [
{ description: "Description 1", number: 30, price: 3.5 },
{ description: "Description 2", number: 33, price: 4 },
{ description: "Description 3", number: 40, price: 4.5 }
]}

Do you want to attempt to reselect the last record? This function below uses the same method you described above and has been working for ages. What you posted above should work. What makes you say it is not working?
function refreshGrid(gridID) {
var grid = $('#' + gridID).data('kendoGrid');
var selectedItem = grid.dataItem(grid.select());
grid.dataSource.read();
grid.refresh();
if (selectedItem != null && selectedItem.uid != null) {
var row = grid.tbody.find('tr[data-uid="' + selectedItem.uid + '"]');
row.addClass("k-state-selected");
grid.select(row);
grid.select(grid.table.find('tr').first());
}
}

k-rebind="gridOptions"
This event will rebind the grid whenever gridOptions are changed.

Related

How to eliminate the empty rows from the jTable jQuery?

I have two jTables in my web page, which loads data from a database. The first jTable fetches the data directly from the database and the second table loads its data according to the selected data in the first table.
The problem now I am facing is, in-case if there are no data to be fetched for the second table, from the particular selected row, the rows are displaying empty.
For example, I have selected a data in the table 1, but since there is no data related to the selected data, the second table is displaying empty rows.
How to hide or not to fetch if the rows were completely empty at the same time if the row has even a single entry I wanted to display that row.
I am using python in the back end to fetch the data. So, do I need to make changes in my python code or do I need to make a change in the front end jQuery or CSS.
I have tried to use the jQuery, it is not working as expected.
My first jTable code is:
$('#SelectCode').jtable({
selecting: true,
paging: true,
actions: {
listAction:// my back end connection here
},
fields: {
codes: {
title: 'Code',
},
name:{
title: 'Name',
},
},
selectionChanged: function () {
var $selectedRows = $('#SelectCode').jtable('selectedRows');
if ($selectedRows.length > 0) {
$selectedRows.each(function () {
var record = $(this).data('record');
Code = record.event_codes;
$('#System').jtable('load',{code:(SelectedCode)});
});
},
});
My second jTable code is:
$('#System').jtable({
selecting: true,
paging: true,
actions: {
listAction:// my back end connection here
},
fields: {
date:{
title:'Date',
},
Time:{
title:'Time'
},
},
});
So, can someone, please help me how can I achieve in eliminating the empty rows from the table.
Thanks,
I have achieved it by adding the following line of codes in my jTable fields:
display: function(data) {
if (data.record.date == null) {
$("#System tr").each(function() {
var cellText = $.trim($(this).text());
if (cellText.length == 0) {
$(this).hide();
}
});
}
return data.record.date;
},

Kendo UI Grid change row detail values from command function without detail collapse

I have a kendo grid with a detail template, which I wish to clear if the user clicks on the clear command in the parent row.
I managed to get this to work, but as soon as I set the value on the dataItem, the row detail collapses, which causes the user to loose his place.
function clearDetails(e) {
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
dataItem.set("City",""); // causes row detail collapse
}
$(document).ready(function () {
$("#grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Customers"
},
},
columns: [{
field: "ContactName",
title: "Contact Name",
width: 240
}, {
field: "Country",
width: 150
}, { command: { text: "Clear", click: clearDetails }, title: " ", width: "180px" }],
detailTemplate: kendo.template($("#myRowDetailTemplate").html())
})
});
Working example:
https://jsbin.com/xuwakol/edit?html,js,output
Is there a way I can still clear the values in the row detail, without it collapsing.
I had the same issue I got around it by using the dataBinding function within the kendo grid.
Basically it checks for an item change event and will cancel the default action to close the grid. This allowed me to continue to use the set method.
Example:
$("#grid").kendoGrid({
dataBinding: function (e) {
if (e.action == "itemchange") {
e.preventDefault();
}
},
});
}
I managed to get this right by not using the set method on the dataItem. http://docs.telerik.com/kendo-ui/api/javascript/data/observableobject#methods-set
I just changed the value on the dataItem, dataItem.City =""; and with the help of jquery selectors cleared the value of the textarea.
function clearDetails(e) {
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
dataItem.City ="";
$(e.currentTarget).closest(".k-master-row").next().find("textarea[name='City']").val("");
}

Select2 - Can't select a value?

Release version (Select 4.0.1)
HTML
<select id="search_customers" style="width: 300px;"></select>
Javascript:
$("#search_customers").select2({
multiple: false,
allowClear: true,
ajax: {
url: "#Url.Action("
SearchCustomers ", "
Home ")",
dataType: 'json',
delay: 250,
data: function(params) {
return {
id: params.term, // search term
};
},
processResults: function(data, params) {
return {
results: data
} // Data is a List<T> of id an text
},
}
});
The dropdown works, and I can see my records, however, when I click on one of the options the box closes, and the selected record isn't shown. My box looks like this
I've tried everything I can think of. The issue appears in all browsers. The data being return is a list of id/text pairs.
Controller code
var customers = this.service.SearchCustomers(id).Select(x => new { id = x.CustomerID, text = x.CustomerName }).ToList();
return Json(customers, JsonRequestBehavior.AllowGet);
My customer ID's had leading spaces for some reason. (Old ERP system), so adding a .Trim() call to the select statement on the customer ID fixed it. Apparently select2 doesn't like " 56", but "56" is fine!

jQGrid celledit in JSON data shows URL Not set alert

I need to load a JSON from server and i want to enable a user to click and edit the value.
But when they edit, it should not call server. i mean i am not going to update immediately. So i dont want editurl. So i tried
'ClientArray' But still it shows Url is not set alert box. But i need
all the edited values when the user click Add Commented Items button this button will fire AddSelectedItemsToSummary() to save those in server
MVC HTML Script
<div>
<table id="persons-summary-grid"></table>
<input type="hidden" id="hdn-deptsk" value="2"/>
<button id="AddSelectedItems" onclick="AddSelectedItemsToSummary();" />
</div>
$(document).ready(function(){
showSummaryGrid(); //When the page loads it loads the persons for Dept
});
JSON Data
{"total":2,"page":1,"records":2,
"rows":[{"PersonSK":1,"Type":"Contract","Attribute":"Organization
Activity","Comment":"Good and helping og"},
{"PersonSK":2,"Type":"Permanant","Attribute":"Team Management",
"Comment":"Need to improve leadership skill"}
]}
jQGRID code
var localSummaryArray;
function showSummaryGrid(){
var summaryGrid = $("#persons-summary-grid");
// doing this because it is not firing second time using .trigger('reloadGrid')
summaryGrid.jqGrid('GridUnload');
var deptSk = $('#hdn-deptsk').val();
summaryGrid.jqGrid({
url: '/dept/GetPersonSummary',
datatype: "json",
mtype: "POST",
postData: { deptSK: deptSk },
colNames: [
'SK', 'Type', 'Field Name', 'Comments'],
colModel: [
{ name: 'PersonSK', index: 'PersonSK', hidden: true },
{ name: 'Type', index: 'Type', width: 100 },
{ name: 'Attribute', index: 'Attribute', width: 150 },
{ name: 'Comment', index: 'Comment', editable: true,
edittype: 'textarea', width: 200 }
],
cellEdit: true,
cellsubmit: 'clientArray',
editurl: 'clientArray',
rowNum: 1000,
rowList: [],
pgbuttons: false,
pgtext: null,
viewrecords: false,
emptyrecords: "No records to view",
gridview: true,
caption: 'dept person Summary',
height: '250',
jsonReader: {
repeatitems: false
},
loadComplete: function (data) {
localSummaryArray= data;
summaryGrid.setGridParam({ datatype: 'local' });
summaryGrid.setGridParam({ data: localSummaryArray});
}
});
)
Button click function
function AddSelectedItemsToSummary() {
//get all the items that has comments
//entered using cell edit and save only those.
// I need to prepare the array of items and send it to MVC controller method
// Also need to reload summary grid
}
Could any one help on this? why i am getting that URL is not set error?
EDIT:
This code is working after loadComplete changes. Before it was showing
No URL Set alert
I don't understand the problem with cell editing which you describe. Moreover you wrote "i need the edited value when the user click + icon in a row". Where is the "+" icon? Do you mean "trash.gif" icon? If you want to use cell editing, how you imagine it in case of clicking on the icon on the row? Which cell should start be editing on clicking "trash.gif" icon? You can start editing some other cell as the cell with "trash.gif" icon ising editCell method, but I don't think that it would be comfortable for the user because for the users point of view he will start editing of one cell on clicking of another cell. It seems me uncomfortable. Probably you want implement inline editing?
One clear error in your code is usage of showSummaryGrid inside of RemoveFromSummary. The function RemoveFromSummary create jqGrid and not just fill it. So one should call it only once. To refresh the body of the grid you should call $("#persons-summary-grid").trigger("refreshGrid"); instead. Instead of usage postData: { deptSK: deptSk } you should use
postData: { deptSK: function () { return $('#hdn-deptsk').val(); } }
In the case triggering of refreshGrid would be enough and it will send to the server the current value from the '#hdn-deptsk'. See the answer for more information.
UPDATED: I couldn't reproduce the problem which you described, but I prepared the demo which do what you need (if I understand your requirements correctly). The most important part of the code which you probably need you will find below
$("#AddSelectedItems").click(function () {
var savedRow = summaryGrid.jqGrid("getGridParam", "savedRow"),
$editedRows,
modifications = [];
if (savedRow && savedRow.length > 0) {
// save currently editing row if any exist
summaryGrid.jqGrid("saveCell", savedRow[0].id, savedRow[0].ic);
}
// now we find all rows where cells are edited
summaryGrid.find("tr.jqgrow:has(td.dirty-cell)").each(function () {
var id = this.id;
modifications.push({
PersonSK: id,
Comment: $(summaryGrid[0].rows[id].cells[2]).text() // 2 - column name of the column "Comment"
});
});
// here you can send modifications per ajax to the server and call
// reloadGrid inside of success callback of the ajax call
// we simulate it by usage alert
alert(JSON.stringify(modifications));
summaryGrid.jqGrid("setGridParam", {datatype: "json"}).trigger("reloadGrid");
});

Performing action a button click event, button being placed inside dojox.grid.DataGrid.

I have a dojox.grid.DataGrid. In this a set of values are being displayed along with last 2 columns being filled up with buttons which are created dynamically according to data being retrieved from database using formatter property in gridStruture. Now i am getting the my grid fine. Buttons are also coming up fine. What i need to do now is when i click on a particular button on that button click event i redirect it to a new URL with a particular value(A) being passes as a query string parameter in that URL. And i don't want my page to be refreshed. Its like when a button is clicked it performs action on some other JSP page and displays message alert("Action is being performed").
My java script code where i have coded for my data grid ::
<script type="text/javascript">
function getInfoFromServer(){
$.get("http://localhost:8080/2_8_2012/jsp/GetJson.jsp?random=" + new Date().getTime(), function (result) {
success:postToPage(result),
alert('Load was performed.');
},"json");
}
function postToPage(data){
alert(data);
var storedata = {
identifier:"ActID",
items: data
};
alert(storedata);
var store1 = new dojo.data.ItemFileWriteStore({data: storedata}) ;
var gridStructure =[[
{ field: "ActID",
name: "Activity ID",
classes:"firstName"
},
{
field: "Assigned To",
name: "Assigned To",
classes: "firstName"
},
{ field: "Activity Type",
name: "Activity Type",
classes:"firstName"
},
{
field: "Status",
name: "Status",
classes: "firstName"
},
{
field: "Assigned Date",
name: "Assigned Date",
classes: "firstName"
},
{
field: "Assigned Time",
name: "Assigned Time",
classes: "firstName"
},
{
field: "Email",
name: "Send Mail",
formatter: sendmail,
classes: "firstName"
},
{
field: "ActID",
name: "Delete",
formatter: deleteact,
classes: "firstName"
}
]
];
//var grid = dijit.byId("gridDiv");
//grid.setStore(store1);
var grid = new dojox.grid.DataGrid({
store: store1,
structure: gridStructure,
rowSelector: '30px',
selectionMode: "single",
autoHeight:true,
columnReordering:true
},'gridDiv');
grid.startup();
dojo.connect(grid, "onRowClick", grid, function(){
var items = grid.selection.getSelected();
dojo.forEach(items, function(item){
var v = grid.store.getValue(item, "ActID");
getdetailsfordialog(v);
function showDialog() {
dojo.require('dijit.Tooltip');
dijit.byId("terms").show();
}
showDialog();
}, grid);
});
}
function sendmail(item) {
alert(item);
return "<button onclick=http://localhost:8080/2_8_2012/jsp/SendMailReminder.jsp?Send Mail="+item+"'\">Send Mail</button>";
}
function deleteact(item) {
alert(item);
return "<button onclick=http://localhost:8080/2_8_2012/jsp/DeleteActivity.jsp?Activity ID="+item+"'\">Delete</button>";
}
</script>
I am getting grid data using $.get call. In the above code field Email and ActID are actually buttons being created when each time function sendmail and deleteact are being called up in formatter. Grid is displayed. Also the value of alert(item) in both functions are coming up right that is there respective values. Like for alert(item) in Delete i am getting ActID and alert(item) in sendmail getting "shan#gmail.com" Now i want that on a particular button click(button in Sendmail column) my page
http://localhost:8080/2_8_2012/jsp/SendMailReminder.jsp?Send Mail="+item+"'
and button click in Delete column this page
http://localhost:8080/2_8_2012/jsp/DeleteActivity.jsp?Activity ID="+item+"'\"
opens up with value of items being retrieved from database. I have applied a rowClick event also which is also causing problem as when i click u button my Rowclick event fires instead of button click event. How to do this. I thought of applying click event to each button on grid. But there ID i don't know. Please help me on this one. Thanks..
I think, what you need is adjusting your server-side code to handle ajax post requests for sending mail and use dojo.xhrPost method when user clicks button. Your JS code may look like this:
function sendMailHandler(evt, item) {
dojo.xhrPost({
url: "/2_8_2012/jsp/SendMailReminder.jsp",
content: {
'SendMail': item
},
error: function() {
alert("Sent failure");
},
load: function(result) {
alert("Email sent with result: " + result);
}
});
dojo.stopEvent(evt);
}
function sendmail(item) {
return "<button onclick='sendMailHandler(arguments[0], \"" + item + "\")'>Send Mail</button>";
}
Note that dojo.stopEvent(evt); in sendMailHandler is used to stop event bubbling and prevents RowClick raising.
There is also dojo.xhrGet with similar syntax to perform ajax GET requests, which you can use instead of jQuery's $.get. You can also use dojo.xhrGet instead of dojo.xhrPost in my example, because there is chance that it will work with your back-end without tweaking, but POST (or ajax form submission) would be more semantically correct.
And about "Tried to register an id="something", you should adjust your code to avoid IDs duplication. Or show your code causing errors.

Categories