Kendo UI reload treeview - kendo-ui

I load a complex treeview with kendo ui via ajax because I need to load the tree with one request (works fine):
$(document).ready(function() {
buildTree();
});
function buildTree(){
$.getJSON("admin_get_treedata.php", function (data) {
$("#treeview").kendoTreeView({
select: function(item) { editTreeElement(item,'tree'); },
dataSource: data
});
})
}
If I try to reload the complete tree after changing some data via ajax the new build tree does not work correct and does not update the text.
$.ajax({
type: 'POST',
url: 'ajax/ajax_update_layer.php',
data: {
layerid:id,
...
},
success: function(data){
buildTree();
}
});
What can Ido?
Thanks
Sven

try this on ajax success callback
var data = $("#treeView").data('kendoTreeView');
data.dataSource.read();

I got mine to work.
This is what I did:
Function that creates the tree view:
function CreateNotificationTree(userId)
{
var data = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: "../api/notifications/byuserid/" + userId,
contentType: "application/json"
}
},
schema: {
model: {
children: "notifications"
}
}
});
$("#treeview").kendoTreeView({
dataSource: data,
loadOnDemand: true,
dataUrlField: "LinksTo",
checkboxes: {
checkChildren: true
},
dataTextField: ["notificationType", "NotificationDesc"],
select: treeviewSelect
});
function treeviewSelect(e)
{
var $item = this.dataItem(e.node);
window.open($item.NotificationLink, "_self");
}
}
Modification & data source refresh:
$('#btnDelete').on('click', function()
{
var treeView = $("#treeview").data("kendoTreeView");
var userId = $('#user_id').val();
$('#treeview').find('input:checkbox:checked').each(function()
{
var li = $(this).closest(".k-item")[0];
var notificationId = treeView.dataSource.getByUid(li.getAttribute('data-uid')).ID;
if (notificationId == "undefined")
{
alert('No ID was found for one or more notifications selected. These notifications will not be deleted. Please contact IT about this issue.');
}
else
{
$.ajax(
{
url: '../api/notifications/deleteNotification?userId=' + userId + '&notificationId=' + notificationId,
type: 'DELETE',
success: function()
{
CreateNotificationTree(userId);
alert('Delete successful.');
},
failure: function()
{
alert('Delete failed.');
}
});
treeView.remove($(this).closest('.k-item'));
}
});
});
Hope that helps.

Related

Kendo Multiselect with pre determined values

I have looked everywhere and cant seem to get this figured out. My issue..
I have 1 kendo dropdown list and 3 kendo mutliselects. each selection filters the next object. Dropdownl => MS1 => MS2 => MS3...
At times, a user may come into this page with a predetermined set of values that need to be selected in the above objects. 1 for the DD and 1+ for the MS.
I can get the dropdown to populate and have the corrected selected item. I can get the first MS to populate with the correct values but not select the values that are needed (0 values are selected) and the next 2 dont work cause i cant get past the first MS properly. I feel like I am running into some kind of sync/async issues that I cant wrap my head around.
See code below. I have included all my data sources, object setups and functions that i felt were relevant (maybe too much). The important function is prePopulateSelectedValues. this is the one that gets called to use the values to select the DD list values. I only included one of the updateLineShopGroupMS (for example) as the other update functions are basically the same. Right now I am stuck on 2 different versions of code which both provide the same results - a promise and non-promise version which you can see in prePopulateSelectedValues.
Thank you in advance
var lineShopGroupDataSource = new kendo.data.DataSource({
serverFiltering: false,
transport: {
read: {
url: "/Base/GetLineShopGroupsFilteredByLocationGroup",
type: "GET",
dataType: "json",
data: function (e) {
return {
LocationGroupId: getDropDownLists("LocationGroupId").value()
};
}
}
}
});
var locationGroupDataSource = new kendo.data.DataSource({
transport: {
read: {
type: "GET",
dataType: "json",
url: '/Base/GetLocationGroupNames',
data: function (e) {
return {
LocationGroupId: getDropDownLists("LocationGroupId").value()
};
}
}
}
});
var substationDataSource = new kendo.data.DataSource({
transport: {
read: {
type: "GET",
dataType: "json",
url: '/Base/GetSubstationFilteredByLineShopGroup',
data: function (e) {
let ids = getMultiSelect("LineShopGroup").value();
return {
LineShopIds: ids.toString()
};
}
}
}
});
var circuitDataSource = new kendo.data.DataSource({
transport: {
read: {
type: "GET",
dataType: "json",
url: '/Base/GetCircuitFilteredBySubstation',
data: function (e) {
let ids = getMultiSelect("Substation").value();
return {
SubstationIds: ids.toString()
};
}
}
}
});
function setUpCircuit() {
$("#Circuit").kendoMultiSelect({
autoBind: false,
enable: false,
placeholder: "Select Circuit(s)...",
dataTextField: "Text",
dataValueField: "Value",
dataSource: circuitDataSource,
filter: "contains",
change: function () {
getHiddenCircuitList();
}
});
}
function setUpSubstation() {
$("#Substation").kendoMultiSelect({
autoBind: false,
enable: false,
dataTextField: "Text",
dataValueField: "Value",
placeholder: "Select Substation(s)...",
dataSource: substationDataSource,
filter: "contains",
change: function () {
if (document.getElementById('Circuit')) {
updateCircuitMS();
}
getHiddenSubstationList();
}
});
}
function setUpLineShopGroup() {
$("#LineShopGroup").kendoMultiSelect({
autoBind: false,
dataTextField: "Text",
dataValueField: "Value",
headerTemplate: "<label style='padding-left: 10px;'><input type='checkbox' id='selectAllLineShopGroups'> Select All</label>",
dataSource: lineShopGroupDataSource,
placeholder: "Select Line Shop/Group...",
change: function () {
if (document.getElementById('Substation')) {
updateSubstationMS();
}
checkAllFlag("LineShopGroup");
getHiddenLineShopList();
}
});
}
function setUpLocationGroupId() {
$("#LocationGroupId").kendoDropDownList({
autoBind: true,
dataTextField: "Text",
dataValueField: "Value",
optionLabel: "Select Location Group...",
dataSource: locationGroupDataSource,
change: function () {
if (document.getElementById('LineShopGroup')) {
updateLineShopGroupMS();
}
}
});
}
function prePopulateSelectedValues(locGroupList, lineShopGroupsList, substationList, circuitList) {
if (locGroupList !== "0") {
var locGrpDD = $('#LocationGroupId').data('kendoDropDownList');
var lineShopMS;
$("#LocGroupString").val(locGroupList);
locGrpDD.value(locGroupList);
if (document.getElementById('LineShopGroupString')) {
debugger
var promise = new Promise(function (resolve, reject) {
debugger
resolve(function () {
updateLineShopGroupMS();
});
});
promise.then(function() {
//we have our result here
debugger
var lineShopMS = $('#LineShopGroup').data('kendoMultiSelect');
return lineShopMS; //return a promise here again
}).then(function(result) {
//handle the final result
debugger
$("#LineShopGroupString").val(lineShopGroupsList);
result.value([lineShopGroupsList]);
}).catch(function (reason) {
debugger
});
}
if (document.getElementById("SubstationString")) {
updateSubstationMS();
var substationMS = $('#Substation').data('kendoMultiSelect');
$("#SubstationString").val(substationList);
substationMS.value(substationList);
}
if (document.getElementById("CircuitsString")) {
updateCircuitMS();
var circuitMS = $('#Circuit').data('kendoMultiSelect');
$("#CircuitsString").val(circuitList);
substationMS.value(circuitList);
}
}
}
function updateLineShopGroupMS() {
var msObj = getMultiSelect('LineShopGroup');
var ddValue = getDropDownLists('LocationGroupId').value();
if (ddValue !== '') {
msObj.enable();
lineShopGroupDataSource.read();
}
else {
msObj.enable(false);
msObj.value([]);
}
}

Kndo TreeView LoadOnDemand not hitting the server

for my kendo treeview, i set load on demand to true but it is not hitting the server to load childs, because the 'children' property is set for the datasource model, even its empty.
homogeneous = new kendo.data.HierarchicalDataSource({
transport: {
read: {
type: 'POST',
contentType: "application/json; charset=utf-8",
url: obj.DataSourcesURL,
dataType: "json"
},
parameterMap: function (options) {
if (!options.Id) {
options.Id = null;
}
if (options.filter) {
options.Search = options.filter.filters[0].name;
}
else {
options.Search = '';
}
return JSON.stringify(options);
}
},
schema: {
data: "d",
errors: function (response) {
console.log(response);
console.log("errors");
},
model: {
hasChildren: "hasChild",
children:'items',
id: "Id"
}
}
});
And treeView code is
$treeView.kendoTreeView({
dataTextField: 'Description',
checkboxes: {
checkChildren: true
},
dataSource: homogeneous,
loadOnDemand: loadOnDemand,
check: function () {
var checkedNodes = [];
var treeView = $treeView.data("kendoTreeView");
getCheckedNodes(treeView.dataSource.view(), checkedNodes);
setMessage(checkedNodes.length);
},
dataBound: function (e) {
if (e !== undefined)
resetCheckedNodes(e.sender.dataItems());
},
messages: {
loading: "Laden..."
},
expand: function (e) {
var dataItem = this.dataItem(e.node);
}
});
Try to set hasChildren like this in your schema:
schema: {
data: "d",
errors: function (response) {
console.log(response);
console.log("errors");
},
model: {
hasChildren: function(e) {
return e.items && e.items.length;
},
children:'items',
id: "Id"
}
}
And also from your question I am not sure do you even get any data or it is only Children data that is not returned. Maybe you could also show how your data structure look like.

On confirm delete?

i have this mootools code that on click of a button deletes the record,now i want when the user clicks the delete button a confirm dialog pop up asking am i sure that i want to delete the record with the answers yes and no...here is my code...if the user answers yes to continue this request if he answers no dont continue,it would be also great if i had another message saying that the record was deleted after he clicked yes...
<script>
window.addEvent('domready',function() {
$$('a.delete').each(function(el) {
el.addEvent('click',function(e) {
e.stop();
var parent = el.getParent('div');
var request = new Request({
url: '/delete.php',
link: 'chain',
method: 'get',
data: {
'delete': parent.get('id').replace('record-',''),
ajax: 1
},
onRequest: function() {
new Fx.Tween(parent,{
duration:300
}).start('background-color', '#fb6c6c');
},
onSuccess: function() {
new Fx.Slide(parent,{
duration:300,
onComplete: function() {
parent.dispose();
}
}).slideOut();
}
}).send();
});
});
});
</script>
it's simple.
if (confirm('message')){
// code when yes
}
else {
// code when no
}
hence.
$$('a.delete').each(function (el) {
el.addEvent('click', function (e) {
e.stop();
var parent = el.getParent('div');
if (confirm('are you sure you want to delete this?')) {
new Request({
url: '/delete.php',
link: 'chain',
method: 'get',
data: {
'delete': parent.get('id').replace('record-', ''),
ajax: 1
},
onRequest: function () {
new Fx.Tween(parent, {
duration: 300
}).start('background-color', '#fb6c6c');
},
onSuccess: function () {
new Fx.Slide(parent, {
duration: 300,
onComplete: function () {
parent.dispose();
}
}).slideOut();
}
}).send();
} // confirm
});
});

show ajax-loader.png on a MVC3 form submit in a Jquerymobile application

I have a mobile application with MVC3 and Jquerymobile. At form submission (with ajax function) I want to display loading icon (ajax-loader.png) while submit and redirect.
Thanks!
my ajax function:
$("#add").click(function () {
$.validator.unobtrusive.parse($('form')); //added
if ($("form").valid()) {
var IDs = new Array($("#SelectedProduct").val(), $("#SelectedAccount").val(), $("#SelectedProject").val(), $("#SelectedTask").val(), $("#date").val(), $("#duration").val());
$.ajax({
url: '#Url.Action("SaveLine", "AddLine")',
type: 'post',
data: { ids: IDs },
dataType: 'json',
traditional: true,
success: function (data) {
if (data.success == true) {
$("#ajaxPostMessage").html(data.Success);
$("#ajaxPostMessage").addClass('ajaxMessage').slideDown(function () {
window.location.href = '#Url.Action("Index", "AddLine")';
}).delay(1800)
}
else {
$("#ajaxPostMessage").html(data.Error);
$("#ajaxPostMessage").addClass('ajaxMessage');
$("#ajaxPostMessage").show();
}
}
});
}
return false;
});
I would do something like this:
Ajax = {
Submit: function() {
Ajax.Loading();
//ajax stuff
//Ajax.Message('form complete, blah blah');
},
Loading: function() {
$('#ajax').html('ajax-loader.png');
},
Message: function(msg) [
$('#ajax').html(msg);
}
}

jQuery dialog for a partial view is not opening modal

I have built a jquery dialog to show a partial view for entering data.
I have built the action link:
#Html.ActionLink("Add New Service Provider", "PartialNewCust", "Customer", null, new { #class = "addServiceProviderLink" })
I have the controller action:
public ActionResult PartialNewCust()
{
return PartialView();
}
And the div / jQuery code:
<div id="AddServiceProvDialog" title="Add Service Provider"></div>
<script type="text/javascript">
var linkObj;
$(function () {
$(".addServiceProviderLink").button();
$('#AddServiceProvDialog').dialog(
{
autoOpen: false,
width: 400,
resizable: false,
modal: true,
buttons:
{
"Add": function () {
$("#addProviderForm").submit();
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
$(".addServiceProviderLink").click(function () {
linkObj = $(this);
var dialogDiv = $('#AddServiceProvDialog');
var viewUrl = linkObj.attr('href');
$.get(viewUrl, function (data) {
dialogDiv.html(data);
//validation
var $form = $("#addProviderForm");
// Unbind existing validation
$form.unbind();
$form.data("validator", null);
// Check document for changes
$.validator.unobtrusive.parse(document);
// Re add validation with changes
$form.validate($form.data("unobtrusiveValidation").options);
//open dialog
dialogDiv.dialog('open');
return false;
});
});
});
The partial view renders fine but opens a new page and does not come up as a modal dialog.
What am I doing wrong.
On a side note: my autocomplete code is also not working by my jQuery datetime picker is...
$(document).ready(function()
{
$(".date").datepicker();
}
);
$(document).ready(function () {
$("#CustByName").autocomplete(
{
source: function (request, response) {
$.ajax(
{
url: "/Cases/FindByName", type: "GET", dataType: "json",
data: { searchText: request.term, maxResults: 10 },
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
label: item.CustomerName,
value: item.CustomerName,
id: item.CustomerID
}
})
);
}
});
},
minLength: 3
});
});
My guess is that you misplaced the return false statement in the button's click handler, thus the default behavior is not prevented as you expect, and the link is simply followed:
$(".addServiceProviderLink").click(function () {
...
$.get(viewUrl, function (data) {
dialogDiv.html(data);
...
dialogDiv.dialog('open');
// this return statement should be in the "click" handler,
// not in success callback of the .get() method !
return false;
});
});
Your code should then be:
$(".addServiceProviderLink").click(function () {
...
$.get(viewUrl, function (data) {
...
});
// return here to prevent default click behavior
return false;
});

Resources