Update the Kendo UI page when kendoAutoComplete is selected - javascript

I've added in a kendoAutoComplete widget to a template Kendo UI. The widget is linked to the employee names from employees-list.json and suggesting names correctly.
<p>Search Member: <input id="member-auto-complete" /></p>
<script>
$('#member-auto-complete').kendoAutoComplete({
dataTextField: "EmployeeName",
dataSource: {
transport: {
read: {
url: './content/employees-list.json',
crossDomain: true,
dataType: "jsonp",
jsonp: false,
jsonpCallback: "callback_el",
}
},
},
change: onCriteriaChange,
});
</script>
I'm now unsure how to make the page update when a suggested name is clicked on, the way that it does when you just click on the employee from the side list menu.
I think it is related to the employee variable not updating in the onCriteriaChange function
function onCriteriaChange() {
var employeeList = $("#employees-list").data("kendoListView"),
employee = employeeList.dataSource.getByUid(employeeList.select().attr("data-uid")),
employeeQuarterSales = $("#employee-quarter-sales").data("kendoChart"),
employeeAverageSales = $("#employee-average-sales").data("kendoChart"),
teamSales = $("#team-sales").data("kendoChart"),
employeeSales = $("#employee-sales").data("kendoScheduler"),
startDate = $("#start-date").data("kendoDatePicker"),
endDate = $("#end-date").data("kendoDatePicker"),
filter = {
EmployeeID: employee.EmployeeID,
startDate: kendo.format("{0:MM/dd/yyyy hh:mm:ss}", startDate.value()),
endDate: kendo.format("{0:MM/dd/yyyy hh:mm:ss}", endDate.value())
},
template = kendo.template($("#employeeBioTemplate").html());
console.log(employee)
$("#employeeBio").html(template(employee));
employeeSales.dataSource.filter({
field: "EmployeeID",
operator: "eq",
value: employee.EmployeeID
});
teamSales.dataSource.read(filter);
employeeQuarterSales.dataSource.read(filter);
employeeAverageSales.dataSource.read(filter);
}
Here's the github repo
https://github.com/frankli-n/Kendo-UI-for-jQuery/blob/main/apptemplates/dashboard/index.html

Related

How to get selected checkbox based on first selected dropdown after refresh the page?

I have dropdown, checkboxes and button submit. First, the user will choose at dropdown (position of work). Second, the user will select the checkbox and after that submit the data. Here, after refresh it should be appear back the previous selected dropdown and checkbox. But, I did not get it. Anyone here have more better solution?
JavaScript Dropdown
//dropdown position
$("#dropdown").kendoDropDownList({
optionLabel: "- Select Position -",
dataTextField: "functionName",
dataValueField: "hrsPositionID",
dataSource: {
transport:{
read: {
url: "../DesignationProgramTemplate/getData.php",
type: "POST",
data: function() {
return {
method: "getDropdown",
}
}
},
},
},
change: onChange
}).data('kendoDropDownList');
dropdownlist = $("#dropdown").data("kendoDropDownList");
Checkbox treeview (Kendo UI)
homogeneous = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: serviceRoot,
dataType: "json"
}
},
schema: {
model: {
id : "ehorsProgramID",
hasChildren: false,
children : "items"
}
},
filter: { field: "module", operator: "startswith", value: "Accounting" }
});
$("#AccountingTree").kendoTreeView({
check: onCheck,
checkboxes: { checkChildren: true } ,
// select: onSelect,
dataSource: homogeneous,
dataBound: function(){
this.expand('.k-item');
},
dataTextField: ["module","groupname","ehorsProgramName"]
});
AJAX for submit button
//AJAX call for button
$("#primaryTextButton").kendoButton();
var button = $("#primaryTextButton").data("kendoButton");
button.bind("click", function(e) {
var test = $("#dropdown").val()
$.ajax({
url: "../DesignationProgramTemplate/getTemplate.php",
type: "post",
data: {'id':test,'progid':array},
success: function () {
// you will get response from your php page (what you echo or print)
kendo.alert('Success'); // alert notification
//refresh
//location.reload("http://hq-global.winx.ehors.com:9280/ehors/HumanResource/EmployeeManagement/DesignationProgramTemplate/template.php");
},
});
});
JavaScript for check checkboxes
function checkedNodeIds(nodes, checkedNodes) {
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].checked) {
checkedNodes.push(nodes[i].id);
}
if (nodes[i].hasChildren) {
checkedNodeIds(nodes[i].children.view(), checkedNodes);
}
}
}
var array = [];
function onCheck() {
var checkedNodes = [],treeView = $("#AccountingTree").data("kendoTreeView"),message;
var checkedNodes2 = [],treeView2 = $("#AdminSystemTree").data("kendoTreeView"),message;
var checkedNodes3 = [],treeView3 = $("#FnBTree").data("kendoTreeView"),message;
var checkedNodes4 = [],treeView4 = $("#HumanResourceTree").data("kendoTreeView"),message;
var checkedNodes5 = [],treeView5 = $("#InventoryManagementTree").data("kendoTreeView"),message;
var checkedNodes6 = [],treeView6 = $("#SalesMarketingTree").data("kendoTreeView"),message;
checkedNodeIds(treeView.dataSource.view(), checkedNodes);
checkedNodeIds(treeView2.dataSource.view(), checkedNodes);
checkedNodeIds(treeView3.dataSource.view(), checkedNodes);
checkedNodeIds(treeView4.dataSource.view(), checkedNodes);
checkedNodeIds(treeView5.dataSource.view(), checkedNodes);
checkedNodeIds(treeView6.dataSource.view(), checkedNodes);
if (checkedNodes.length > 0) {
message = checkedNodes.filter(x => !!x).join(",");
array = checkedNodes.filter(x => !!x);
} else {
message = "No nodes checked.";
}
}
Output
JavaScript for accessing the dataItem
// cookies
var values = ["LA1","LA6","LA12"]; //array nnti array ni la localstorage/cookies
var setTreeViewValues = function(values) {
var tv = $("#AccountingTree").data("kendoTreeView");
document.write(JSON.stringify(tv));
tv.forEach(function(dataItem) {
alert("test");
if (dataItem.hasChildren) {
var childItems = dataItem.children.data();
//document.write(JSON.stringify(childItems[0].items[0].programID));
}
// document.write(JSON.stringify(dataItem.items));
if (values.indexOf(childItems[0].items[0].programID) > -1) {
dataItem.set("checked", true);
}
});
};
setTreeViewValues(values);
console.log(datasource.data()[0].hasChildren);
// end cookies
So without knowing how you are binding the existing values to the page I am assuming you will be calling the page state somewhere within your Page loading.
So I have prepared a dojo that shows two different ways of setting the checked state of the items.
https://dojo.telerik.com/EhaMIDAt/8
1. Setting at the DataSource Level
So when setting up the datasource you can add an extra attribute to your collection called checked this will then set the checked value for the item or children items when loaded. using the example I have in the dojo:
{
id: 9,
text: "Reports",
expanded: true,
spriteCssClass: "folder",
items: [{
id: 10,
text: "February.pdf",
spriteCssClass: "pdf"
},
{
id: 11,
text: "March.pdf",
spriteCssClass: "pdf",
checked: true
},
{
id: 12,
text: "April.pdf",
spriteCssClass: "pdf"
}
]
}
this will set the checked state to true for you and show the checkbox as checked.
2. Manually Set the values after loading all the DataSources.
So I have done this on a button click but this could easily be done on a ready state or some other trigger if needed. Here the button when clicked will find the node in the tree with the text Research.pdf and either set it in a checked or unchecked state for you.
$('#checked').bind('click', () => {
var box = $("#treeview").data("kendoTreeView").findByText('Research.pdf').find('input[type="checkbox"]');
box.prop('checked', !box.is(':checked'));
});
Again the sample it taken from dojo link above. Hopefully this gives you a start on getting the values set according to your specific requirements.
I would probably have the value checked state set when you load the datasource for the treeview.

how to solve Trying to get property 'bids' of non-object error

I want to display data from bid table in a form of datatable. But I get this error
"Trying to get property 'bids' of non-object" if it doesn't have bids.The bids model is connected to auction model and the auction model is connected to media site model. How to make it display blank record if it doesn't have data.
Here is my controller:
<?php
namespace App\Http\Controllers;
use App\Auction;
use App\Bid;
use App\User;
use App\Media;
use App\MediaSite;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class MediaSiteController extends Controller
{
public function show(MediaSite $mediaSite)
{
$auction = $mediaSite->auction;
$bids = $auction->bids;
return view('admin.media-site.show', ['mediaSite' => $mediaSite,'auction' => $auction], compact('auction'));
}
My view:
<body>
<div id="datatable-bid"></div>
</body>
<script>
$(document).ready(function () {
var datatableBid = $('#datatable-bid').mDatatable({
// datasource definition
data: {
type: 'local',
source: {!! json_encode($auction->bids) !!},
pageSize: 10
},
// layout definition
layout: {
theme: 'default', // datatable theme
class: '', // custom wrapper class
scroll: false,
footer: false // display/hide footer
},
// column sorting
sortable: true,
pagination: true,
search: {
input: $('#panel-search')
},
// columns definition
columns: [
{
field: "price",
title: "Price",
}, {
field: "month",
title: "Month",
},{
field: "user_id",
title: "User Id",
}
]
});
</script>
Here is my error:
Trying to get property 'bids' of non-object
place following after $auction = $mediaSite->auction;
if($auction){
$bids = $auction->bids;
}else{
//put following line or whatever you need to do if there is no data comes
$auction = [];
}
In the show() function make these changes
$auction = $mediaSite->auction;
if($auction) {
$bids = $auction->bids;
} else {
$bids = [];
}
// now send $bids to view along with $auction
// may be like this
// return view(..., compact($auction, $bids));
Then, in your view make this change
// datasource definition
data: {
type: 'local',
source: {!! json_encode($bids) !!},
pageSize: 10
},
See if this helps.

Filtering in Telerik Kendo Multiselect

Hi I have a simple select in my mvc view....
<select id="msProducts" multiple style="width:100%;"></select>
which is converted to a Kendo Multiselect using Javascript/JQuery
$(document).ready(function () {
//products multi-select
$("#msProducts").kendoMultiSelect({
placeholder: "Select Product(s)",
dataTextField: "ProductNameText",
dataValueField: "ProductNameValue",
dataSource: {
type: "json",
serverFiltering: true,
transport: {
read: {
url: "Home/Products"
}
}
}
});
});
My Contoller has:
'GET: Home/Products
<HttpGet>
Function Products() As JsonResult
Dim DiaryProductList As List(Of ProductsModel) = ProductsModel.GetProducts
Return Json(DiaryProductList , JsonRequestBehavior.AllowGet)
End Function
My ProductsModel Class is:
Public Class ProductsModel
Public Property ProductNameText As String
Public Property ProductNameValue As String
Public Shared Function GetProducts() As List(Of ProductsModel)
Dim ProductList = New List(Of ProductsModel)
Dim dc As New DBDataContext
Try
Dim ProductsQuery = (From pIn dc.Products
Where p.ProductStatus <> "discontinued"
Select New With {.ProductNameValue = p.ProductName,
.ProductNameText = p.ProductName}).OrderBy(Function(lst) lst.ProductNameValue)
For Each r In ProductsQuery
ProductList.Add(New ProductsModel() With {.ProductNameValue = r.ProductNameValue,
.ProductNameText = r.ProductNameText})
Next
Catch ex As Exception
ProductList.Add(New ProductsModel() With {.ProductNameValue = "",
.ProductNameText = ex.Message})
Finally
dc.Connection.Close()
End Try
Return ProductList
End Function
End Class
My problem is that although the muti-select gets populated (with some 5000+ products) the dropdown is not filtering as a user types. For example if I beging typing the word CAKE. As soon as I type C the I-beam disappears and after a second or two the dropdown drops for a brief moment and then disappears clearing the multi-select completely. The only way I can populate at the moment is type the letter A, wait and then scroll through the complete list and select what I need, repeating for each item I need. Have I missed something? Should I introduce paging in order to limit the data?
Thanks
Based on the links provided by Ademar I've changed my code so that I have the following which works....
//products multi-select
// ms datasource
var ms_dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "Home/Products",
type: "GET",
dataType: "json"
}
},
schema: {
model: {
fields: {
"ProductName": {
type: "string"
}
}
}
}
});
// ms widget options
var ms_options = {
autoBind: false,
minLength: 4,
maxSelectedItems: 25,
dataTextField: "ProductName",
dataValueField: "ProductName",
filter: "contains",
placeholder: "Select Product(s)",
dataSource: ms_dataSource
};
// create ms widget
$("#msProducts").kendoMultiSelect(ms_options);
I have also amended my Product Class so that it give just a list of product names that I use as both the tag text and value in the multiselect.

Extending kendo multiselect and working with MVVM

I'm trying to extend a kendo multiselect so that it has a default data source as well as templates. It's all working except the pre-loaded values in the MVVM object. When I start updating the exented multiselect, the value of the MVVM gets updated, the initial items are just not pre-loaded:
kendo.ui.plugin(kendo.ui.MultiSelect.extend({
init: function(element, options) {
var ds = new kendo.data.DataSource({
type: "json",
serverFiltering: true,
transport: {
read: {
url: "/SecurityEntities",
dataType: "json"
},
parameterMap: function(data) {
return {
prefixText: '',
count: 5,
getUsers: true,
getGroups: false
};
}
},
schema: {
data: function(data) {
console.log($.parseJSON(data));
return $.parseJSON(data);
}
}
});
options = options == null ? {} : options;
options.itemTemplate = "...";
options.tagTemplate = "...";
options.dataSource = ds;
kendo.ui.MultiSelect.fn.init.call(this, element, options);
},
options: {
name: 'EntityMultiSelect'
}
}));
kendo.data.binders.widget.entitymultiselect =
kendo.data.binders.widget.multiselect;
Then my html is:
<div data-bind="value: machine.Managers" data-role="entitymultiselect"
data-delay="400" data-animation="false"
data-placeholder="Select users to notify"></div>
And I am binding the whole container to the page's viewModel object.
I've seen other people have issues with this very problem and added the
kendo.data.binders.widget.entitymultiselect =
kendo.data.binders.widget.multiselect;
(And yes that does seem like a bug)
But it still doesn't work.
When there are already values in Machine.Managers, it doesn't load them. However, if I add values to the multiselect, they get added to Machine.Managers .
EDIT:
I've added a live example
At least in your demo it's a trivial problem: your data-value-field is wrong. As a result, the binder can't match the selected elements.
Instead of
<div data-role="entitymultiselect"
data-bind="value: selected"
data-value-field="ProductId"></div>
you need
<div data-role="entitymultiselect"
data-bind="value: selected"
data-value-field="ProductID"></div>
(working demo)
Since you're not defining the value field in the code in your question, it might be the same issue.

kendoui: How to display foreign key from remote datasource in grid

i have a kendoui grid which list claims. one of the columns is lenders which is a foreign key reference to the lenders table. what i want is to be able to display the lender name in the grid instead of its id reference.
ive setup the lenders datasource as follows
var dsLenders = new kendo.data.DataSource({
transport: {
read: {
url: "../data/lenders/",
dataType: "jsonp"
},
parameterMap: function(options, operation) {
if (operation === "read") {
return options;
}
}
}
});
and the grid looks like this
$("#gridClaims").kendoGrid({
dataSource: claimData,
autoSync:true,
batch: true,
pageable: {
refresh: true,
pageSizes: true
},
filterable: true,
sortable: true,
selectable: "true",
editable: {
mode: "popup",
confirmation: "Are you sure you want to delete this record?",
template: $("#claimFormPopup").html()
},
navigable: true, // enables keyboard navigation in the grid
toolbar: ["create"], // adds insert buttons
columns: [
{ field:"id_clm", title:"Ref", width: "80px;" },
{ field:"status_clm", title:"Status", width: "80px;" },
{ field:"idldr_clm", title:"Lender", values: dsLenders },
{ field:"type_clm", title:"Claim Type"},
{ field:"value_clm", title:"Value", width: "80px;", format:"{0:c2}", attributes:{style:"text-align:right;"}},
{ field:"created", title:"Created", width: "80px;", format: "{0:dd/MM/yyyy}"},
{ field:"updated", title:"Updated", width: "80px;", format: "{0:dd/MM/yyyy}"},
{ field:"user", title:"User" , width: "100px;"},
{ command: [
{text: "Details", className: "claim-details"},
"destroy"
],
title: " ",
width: "160px"
}
]
});
however its still displaying the id in the lenders column. Ive tried creating a local datasource and that works fine so i now is something to do with me using a remote datasource.
any help would be great
thanks
Short answer is that you can't. Not directly anyway. See here and here.
You can (as the response in the above linked post mentions) pre-load the data into a var, which can then be used as data for the column definition.
I use something like this:-
function getLookupData(type, callback) {
return $.ajax({
dataType: 'json',
url: '/lookup/' + type,
success: function (data) {
callback(data);
}
});
}
Which I then use like this:-
var countryLookupData;
getLookupData('country', function (data) { countryLookupData = data; });
I use it in a JQuery deferred to ensure that all my lookups are loaded before I bind to the grid:-
$.when(
getLookupData('country', function (data) { countryLookupData = data; }),
getLookupData('state', function (data) { stateLookupData = data; }),
getLookupData('company', function (data) { companyLookupData = data; })
)
.then(function () {
bindGrid();
}).fail(function () {
alert('Error loading lookup data');
});
You can then use countryLookupData for your values.
You could also use a custom grid editor, however you'll probably find that you still need to load the data into a var (as opposed to using a datasource with a DropDownList) and ensure that the data is loaded before the grid, because you'll most likely need to have a lookup for a column template so that you're newly selected value is displayed in the grid.
I couldn't quite get ForeignKey working in any useful way, so I ended up using custom editors as you have much more control over them.
One more gotcha: make sure you have loaded your lookup data BEFORE you define the column. I was using a column array that was defined in a variable I was then attaching to the grid definition... even if the lookup data is loaded before you use the grid, if it's defined after the column definition it will not work.
Although this post past 2 years, I still share my solution
1) Assume the api url (http://localhost/api/term) will return:
{
"odata.metadata":"http://localhost/api/$metadata#term","value":[
{
"value":2,"text":"2016-2020"
},{
"value":1,"text":"2012-2016"
}
]
}
please note that the attribute name must be "text" and "value"
2) show term name (text) from the foreign table instead of term_id (value).
See the grid column "term_id", the dropdownlist will be created if added "values: data_term"
<script>
$.when($.getJSON("http://localhost/api/term")).then(function () {
bind_grid(arguments[0].value);
});
function bind_grid(data_term) {
$("#grid").kendoGrid({
dataSource: ds_proposer,
filterable: true,
sortable: true,
pageable: true,
selectable: "row",
columns: [
{ field: "user_type", title: "User type" },
{ field: "user_name", title: "User name" },
{ field: "term_id", title: "Term", values: data_term }
],
editable: {
mode: "popup",
}
});
}
</script>
For those stumbling across this now, this functionality is supported:
https://demos.telerik.com/aspnet-mvc/grid/foreignkeycolumnbinding

Categories

Resources