Kendo UI ListView sorting not working - javascript

I have a sortable list view that does not work. When I drag and drop the items, and the Ajax calls the stored procedure to update the display order, the items just go back to their original order.
The database is being updated, so I know it's not a database issue. There are no error messages and the stored procedure returns "Success". Maybe I have the list view and sortable set up wrong?
var DataSource;
$("#VideoView").kendoListView({
dataSource: {
type: "json",
transport: {
read: {
type: "Get",
contentType: "application/json; charset=utf-8",
url: "../api/Admin_Videos",
dataType: "json"
},
timeout: 120000
},
sort: [{ field: "DisplayOrder", dir: "asc" }],
serverSorting: true
},
dataBound: function () {
$(this.items()).on("dblclick", function () {
data = DataSource[$("div.product").index(this)];
EditVideo(data);
});
},
dataBinding: function() {
DataSource = this.dataSource.data();
},
template: kendo.template($("#VideoViewTemplate").html())
});
$("#VideoView").kendoSortable({
filter: ">div.product",
cursor: "move",
placeholder: function (element) {
return element.clone().css("opacity", 0.1);
},
hint: function (element) {
return element.clone().removeClass("k-state-selected");
},
change: function (e) {
var items = $("#VideoView").data("kendoListView").items();
var itemList = items.children("img");
var newList = '';
for (var i = 0; i < items.length; i++) {
newList = newList + itemList.eq(i).attr("id") + ','
}
newList = newList.substring(0, newList.length - 1);
$.ajax({
type: "Post",
contentType: "application/json; charset=utf-8",
url: "../api/Admin_VideoReorder",
datatype: "json",
data: JSON.stringify({ ID: newList }),
success: function (d) {
// rebind data
$("#VideoView").data("kendoListView").dataSource.read();
}
});
}
});

Related

Kendo combo box retrive selected item with virtual

I have a kendo combo box with virtual enabled and I would like to retrive selected item beacause I need more information after.
I got undefined when I select an item after some virtual loading.
This is my code
$scope.select_item_options = {
dataValueField: "id",
dataTextField: "description_nhl",
template: "#= description #",
virtual: true,
filter: "contains",
change: function(e) {
var selected_index = this.selectedIndex;
if (selected_index < 0) {
delete $scope.work_item.item_id;
} else {
var item = this.dataItem(this.select());
console.log(item);
console.log(this.dataItem(selected_index));
// undefined here
}
$scope.$apply();
},
dataSource: new kendo.data.DataSource({
transport: {
read: {
type: "GET",
url: APP_CONFIG.api.base_url + "/items/itemTypes/AC",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', storageService.getValue('auth_token'));
},
complete: function(result, status) {
if (result.status !== 200 || !result.responseJSON.fn.result.done) {
return httpService.callbackOnError(result.responseJSON, result.status);
}
}
}
},
schema: {
data: 'data',
total: function(data) {
return data.dataCount;
}
},
serverPaging: true,
serverSorting: true,
serverFiltering: true,
pageSize: 5,
sort: {field: "description", dir: "asc"}
})
};
Resolved changing
var item = this.dataItem(this.select());
with
var item = this.dataItem();

kendo ui grid sortable and crud is not working

I have followed this tutorial and brought up the sorting to work but now the crud operation is not working.
If i remove the grid sortable code then the crud is working, but no sort.
I have no idea where i am making mistake to make both sort and crud to work
THis is the code i have
$(document).ready(function () {
function dataSource_change(e) {
var data = this.data();
console.log(data.length); // displays "77"
}
var dataSource = new kendo.data.DataSource({
//pageSize: 20,
transport:{
read:{
url: function() {
return "/makes"},
dataType: "json",
cache: false
},
update: {
url: function (make) {
console.log(make)
return "/makes/"+ make.models[0].id
},
type: "PUT",
dataType: "json",
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token',jQuery('meta[name="csrf-token"]').attr("content")); }
},
destroy: {
url: function (make) {
return "/makes/"+ make.models[0].id
},
type: "DELETE",
dataType: "json"
},
create: {
url: "/makes",
type: "POST",
dataType: "json"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
console.log(options)
return{"make": options.models[0]};
}
else{
return {"make":options};
}
}
},
batch: true,
schema: {
model: {
id: "id",
fields: {
id: { editable: false, nullable: true },
name: { validation: { required: true } },
}
}
}
});
dataSource.bind("change", dataSource_change);
dataSource.fetch();
var grid = $("#grid").kendoGrid({
dataSource: dataSource,
pageable: false,
height: 550,
toolbar: [{name: "create", text: "Add New Make"}],
columns: [
{ field:"name",title:"Makes" },
{ command: ["edit", "destroy"], title: "Action", width: "250px" }],
editable: "inline"
}).data("kendoGrid");
grid.table.kendoSortable({
filter: ">tbody >tr",
hint: $.noop,
cursor: "move",
placeholder: function(element) {
return element.clone().addClass("k-state-hover").css("opacity", 0.65);
},
container: "#grid tbody",
change: function(e) {
console.log(grid)
var skip = grid.dataSource.skip(),
oldIndex = e.oldIndex + skip,
newIndex = e.newIndex + skip,
data = grid.dataSource.data(),
dataItem = grid.dataSource.getByUid(e.item.data("uid"));
var updated_order = []
$('tbody tr').each(function(i){
updated_order.push({ name: $(this).children('td:first').text(), position: i+1 });
});
controller_name = $('#controller_name').val();
$.ajax({
type: "PUT",
url: '/sort',
data: { order: updated_order, controller_name: controller_name }
});
grid.dataSource.remove(dataItem);
grid.dataSource.insert(e.newIndex, dataItem);
}
});
});

Kendo dataSource.add - "Id is not defined"

I'm trying to add some items to a Kendo DataSource to then display in the grid. However, every time I try to save I get Reference Error: Id is not defined.
At first I thought it was because I didn't include Id in my schema but I checked and it looks alright.
var viewModel = new kendo.observable({
orgDataSource: new kendo.data.DataSource({
transport: {
read: {
url: "/Organization/GetAll",
dataType: "json"
},
update: {
url: "/Host/Organization/Edit",
dataType: "json",
type: "POST",
data: {
__RequestVerificationToken: getAntiForgeryToken()
}
},
create: {
url: "/Host/Organization/Create",
dataType: "json",
type: "POST",
data: {
__RequestVerificationToken: getAntiForgeryToken()
}
},
destroy: {
url: "/Host/Organization/Delete",
dataType: "json",
type: "POST",
data: {
__RequestVerificationToken: getAntiForgeryToken()
}
}
},
schema: {
model: {
id: "Id",
fields: {
Id: { type: "number", editable: false, nullable: true },
Name: { type: "string" },
LicenseExpiration: { type: "date" },
LicenseNumber: { type: "number" },
Active: { type: "boolean" },
CreateDate: { type: "date" },
LastModDate: { type: "date" },
AvailableLicenses: { type: "string" },
State: { type: "string" }
}
},
errors: "errorMsg"
},
pageSize: 20,
error: function (e) {
toastr.options = {
"positionClass": "toast-bottom-full-width"
};
toastr.error("There was an error: " + e.errors, "Uh, Oh!");
this.cancelChanges();
},
serverPaging: false,
serverFiltering: false,
serverSorting: false
}),
reloadOrganizations: function () {
this.get("orgDataSource").read();
},
onOrgSave: function (e)
{
var uid = $('input[name="OrgRowUID"]').val();
var tr = $('tr[data-uid="' + uid + '"]'); // get the current table row (tr)
var name = $('input[name="Name"]').val();
var licenseNumber = $('input[name="LicenseNumber"]').val();
var licenseExpiration = $('input[name="LicenseExpiration"]').val();
var email = $('input[name="Email"]').val();
var state = $('input[name="State"]').val();
var logo = $('input[name="ImageUrl]').val();
var active = $('input[name="Active"]').is(":checked");
// get the data bound to the current table row
var orgGrid = $("#OrganizationGrid").data("kendoGrid");
var data = orgGrid.dataItem(tr);
if (data == null)
{
viewModel.orgDataSource.add({ Name: name, LicenseNumber: licenseNumber, LicenseExpiration: licenseExpiration, Email: email, State: state, ImageUrl: logo, Active: active })
orgGrid.saveChanges();
viewModel.orgDataSource.sync();
viewModel.reloadOrganizations();
} else {
data.set("Name", name);
data.set("LicenseNumber", licenseNumber);
data.set("LicenseExpiration", licenseExpiration);
data.set("Email", email);
data.set("State", state);
data.set("ImageUrl", logo);
data.set("Active", active);
}
$("#orgCreateModal").modal('hide');
$("#orgEditModal").modal('hide');
}
});
The error is occurring on this line:
viewModel.orgDataSource.add({ Name: name, LicenseNumber: licenseNumber, LicenseExpiration: licenseExpiration, Email: email, State: state, ImageUrl: logo, Active: active });
The error in FireBug is:
Reference Error: Id is not defined - kendo.all.min.js line 25 > function
It's throwing that error because you're not setting "Id" to anything in your datasource. I had a similar problem a while back and Telerik said you have to give 'id' a valid unique value because they use that internally to keep things straight in the datasource. In your case, you are setting your schema id to "Id", but it doesn't look like your datasource has an "Id" field. I ended up just dumping a guid in there and it fixed my problem.

How to add new tags in select2?

I am trying to get the tags from my api. Everything works fine but I cant able to add new tags. Here is what i tried:
$(function(){
var user_email = localStorage.getItem('email');
var api = localStorage.getItem("user_api_key");
var auth = "apikey" +' ' +(user_email+":"+api);
$('#s2id_id_add-places').select2({
multiple: true,
tags: [],
tokenSeparators: [",", " "],
width: "200px",
ajax: {
placeholder: "Click to enter who",
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", auth);
xhr.setRequestHeader("Content-Type","application/json");
xhr.setRequestHeader("Accept","application/json");
},
url: "https://example.com/api/v3/places/",
dataType: "json",
contentType: "application/json",
processData: true,
quietMillis: 50,
data: function(term) {
return {
term: term
};
},
results: function(data) {
var results = [];
if(data.objects.length > 0) {
for (i=0; i<data.objects.length; i++) {
results.push({id: data.objects[i].id, text: data.objects[i].label, isNew: true});
}
}
return {
results: results
};
},
});
});
By using the above code, I can only get the tags but I cant able to add the new tags. how can i add the new tags?
Please help
$("#e11_2").select2({
createSearchChoice: function(term, data) {
if ($(data).filter( function() {
return this.text.localeCompare(term)===0;
}).length===0) {
return {id:term, text:term};
}
},
multiple: true,
data: [{id: 0, text: 'story'},{id: 1, text: 'bug'},{id: 2, text: 'task'}]
});
You have to create a function like createSearchChoice, that returns a object with 'id' and 'text'. In other case, if you return undefined the option not will be created.

kendo ui grid loading indicator not showing

I am using kendo grid in my html page and every thing working perfectly but one issue i am facing when page loads and i send request to get data it takes 1 or 2 seconds meanwhile grid should show loading indicator as we can see in demo . This is what i am doing
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: api/getdata,
dataType: 'json',
cache: false,
headers: { 'ccode': compCode },
async: false,
data: '?&tableName=' + table + '&userId=' + userId + '&fromDate=' + dateFrom + '&toDate=' + dateto + '&isSearchForClient=' + true,
success: function (result) {
var data = [];
if (result) {
result = result.replace(/&/g, "'");
var jsonResult = JSON.parse(JSON.parse(result));
for (var i = 0; i < jsonResult.length; i++) {
data.push({ Log: jsonResult[i]["Log"], TransactionId: jsonResult[i]["TransactionId"] });
}
var grid = $("#logs").kendoGrid({
dataSource: {
data: data,
schema: {
model: {
fields: {
TransactionId: { type: "string" },
Log: { type: "string" }
}
}
},
pageSize: 10
},
height: 405,
scrollable: true,
detailInit: detailInit,
detailExpand: function (e) {
this.collapseRow(this.tbody.find(' > tr.k-master-row').not(e.masterRow));
},
pageable: {
input: true,
numeric: false
},
columns: [
{ field: 'Log', title: "Audit Logs", encoded: true }]
});
//grid.dataSource.read();
}
}
});

Categories

Resources