Kendo DropDownList Preserve Whitespace in Option - kendo-ui

I am using Kendo UI for JQuery/AngularJS.
I have the following <select> control defined:
<select
kendo-drop-down-list
k-options="myOptions">
</select>
I have a datasource returning JSON with VALUE representing the value for an <option>, and TEXT representing the label for the option.
Unfortunately, the VALUE returns with leading spaces, meant to represent a hierarchy:
[
{VALUE: 1, TEXT: 'Accounting'},
{VALUE: 2, TEXT: ' Accounts Payable'},
{VALUE: 3, TEXT: ' Accounts Receivable'}
]
This should correspond to an group of options like the following:
<option value="1">Accounting</option>
<option value="2"> Accounts Payable</option>
<option value="3"> Accounts Receivable</option>
Below is my definition of options:
$scope.myOptions = {
autoWidth: true,
autoBind: false,
dataTextField: 'TEXT',
dataValueField: 'VALUE',
dataSource: {
transport: {
read: {
url: urlToREST,
dataType: 'json',
type: 'POST',
contentType: "application/json"
},
// needed to send params as JSON
parameterMap: function (data, type) {
const req = {
"QUERY_ID": $scope.queryId
};
return JSON.stringify(req);
}
},
schema: {
type: "json",
data: "resultData"
}
}
};
I need to represent multiple levels of a hierarchy in the options. I felt the best way would be to use Javascript to dynamically create a <pre> section, but it's not working.
Can anyone help me?

I ended up dynamically computing the amount of whitespace required to represent the hierarchy, then adding for each space (the number of spaces is a parameter returned by the remote service call):
function indent(spaceCount) {
return ' '.repeat(spaceCount);
}
$scope.options = {
dataTextField: 'TEXT',
dataValueField: 'VALUE',
template: function(dataItem) {
return kendo.template(indent(dataItem.spaces -1) *4) + '#: DESCRIPTION #')(dataItem);
},
dataSource: {
transport: {
read: {
// read definition
},
// needed to send JSON parameters to the query
parameterMap: function(data, type) {
const req = {
'QUERY_ID': $scope.queryId
};
return JSON.stringify(req);
}
},
schema: {
type: 'json',
data: 'resultData'
}
}
};
The indent function could have been done inline. This could also probably have been refactored into an AngularJS service as well.

I ended up using the template function and specified a table within the template
Which allows me to specify width for each row
#(Html.Kendo().ComboBoxFor(model => model.PersonId)
.DataTextField("FullName")
.DataValueField("Id")
.Value("")
.Filter(FilterType.Contains)
.MinLength(2)
.AutoBind(true)
.Template("<table><tr><td width='200px'>#: data.FullName #</td><td width='100px'> - #: data.EmpId #</td></tr></table>")
.DataSource(s =>

Related

Select2 - Change name="param" to other name for post request

I have the following search box for getting data from backend:
<select class="form-control kt-select2" id="megaagent_rainmaker_select" name="param" multiple="multiple" style="width: 100%"></select>
This is my select2 javascript code:
var rainmakerSelect = function () {
// Private functions
var demos = function () {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
// multi select
$('#megaagent_rainmaker_select').select2({
language: "es",
placeholder: "Escriba y seleccione",
allowClear: true,
maximumSelectionLength: 1,
ajax: {
url: '/admin/megaagent/getrainmaker',
type: "get",
dataType: 'json',
delay: 150,
data: function (params) {
return {
_token: CSRF_TOKEN,
search: params.term // search term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: true
}
});
}
return {
init: function () {
demos();
}
};
}();
jQuery(document).ready(function () {
rainmakerSelect.init();
});
I get results returned and I can select one without problem.
After I select a value, I send update request to backend, this is my payload:
{
"_token": "bPl0hZJQxw5wAxNCqVOOKqrXXwkD5AZZOFPumrpC",
"mc_id": "11",
"megaagent_id": "16",
"megaagent_name": "David Cortada",
"megaagent_business_name": "bsame cambio",
"megaagent_uma_id": "umaid",
"megaagent_api_key": "apikey",
"param": "963",
"megaagent_phone_number": "phone",
"megaagent_email": "email",
"megaagent_address": "address",
"megaagent_facebook": "fb",
"megaagent_instagram": "inst",
"megaagent_twitter": "twi",
"megaagent_linkedin": "link",
"megaagent_image": "image",
"megaagent_status": "Activo"
}
What I want to achieve is to change param name to other on post request (example: "megaagent_rainmaker_id" = "963",.
I changed it in <select name="param"> but that breaks the search, no results are returned when I type in search box.
Does anyone knows the solution for this?
Regards

Kendo UI Multiselect Tag mode - filter based on typed value not passing the typed text to server

This is the code which I am using to bind Multiselect to listbox in javascript. I am not where I am missing, I am not receiving the typed text in ajax call to get values. The method gets called in the controller side and the string parameter which I have returns null.
Implemented based on URL: https://demos.telerik.com/kendo-ui/multiselect/addnewitem
$("#Tags").kendoMultiSelect({
placeholder: "Select your tags",
dataTextField: "Name",
dataValueField: "Id",
autoBind: false,
maxSelectedItems: 5,
minLength: 3,
delay: 2000,
//filter: "startswith",
dataSource: {
transport: {
read: {
url: "/Support/Ticket/GetTags",
dataType: "json"
}
},
serverFiltering:true
}
});
Controller
public JsonResult GetTags(string text)
{
List<Tag> tags = _tagRepository.GetAll(text).ToList();
return Json(tags);
}
As mentioned here https://www.telerik.com/forums/server-filtering-not-working-as-expected#KXcqO6xHoE6NxGuL0T2ZoQ, I think you need to add return data option
$(document).ready(function () {
$("#products").kendoMultiSelect({
placeholder: "Select products...",
dataTextField: "ProductName",
dataValueField: "ProductID",
dataSource: {
type: "odata",
serverFiltering: true,
transport: {
read: {
url: "http://demos.kendoui.com/service/Northwind.svc/Products",
data: function () {
return {
text: $("#products").data('kendoMultiSelect').input.val()
};
}
}
}
}
});
});

How to parse my JSON data to String in KENDO GRID?

how can i format this object Object to its actual values ?
I want this json object to display its actual values in a specific kendo grid column .
Can someone please help me and teach me how to do it ?
This is the image of the kendo grid with the result ,
While here is the code that I am using in my view .
Can please someone help .
contact : new kendo.data.DataSource({
transport:{
read:{
type: "GET",
url:"reservation/list",
dataType:"json",
contentType: "application/json; chartset=utf-8"
},
update: {
url: "contacts/update",
dataType: "json",
type: "POST"
},
destroy: {
url: "contacts/destroy",
dataType: "json",
type:"POST"
},
create: {
url: "contacts/store",
dataType: "json",
type:"POST"
}
},
schema:{
model:{
id:"id",
fields:{
Purpose:
{
type:"string",
validation:{required:true}
},
RoomID:
{
from: "RoomID.room_name",
type: "string"
},
Equipments:
{
from: "Equipments",
type: "string"
},
start:
{
type:"date",
validation:{required:true}
},
end:
{
type:"date",
validation:{required:true}
},
}
}
},
pageSize:10
}),
init : function(e){
$("#grid").kendoGrid({
dataSource: this.contact,
selectable: true,
height:600,
editable: "popup",
filterable: true,
sortable: {
mode: "multiple",
allowUnsort: true,
showIndexes: true
},
toolbar: ["search"],
columns: [
{
field: "Purpose",
title:"Purpose"
},
{
field: "RoomID",
title:"Room",
},
{
field: "Equipments",
title:"Equipments",
},
{
field: "start",
title:"Start",
//template: '#= kendo.toString(kendo.parseDate(start), "MM/dd/yyyy HH:mm:ss")#'
format: "{0:MMM dd,yyyy hh:mm tt}",
parseFormats: ["yyyy-MM-dd'T'HH:mm.zz"]
},
{
field: "end",
title:"End",
//template: '#= kendo.toString(kendo.parseDate(end), "MM/dd/yyyy HH:mm:ss")#'
format: "{0:MMM dd,yyyy hh:mm tt}",
parseFormats: ["yyyy-MM-dd'T'HH:mm.zz"]
},
{
command: ["edit", "destroy"],
title: " ",
width: "250px"
}
],
pageable:{
pageSize:10,
refresh:true,
buttonCount:5,
messages:{
display:"{0}-{1}of{2}"
}
}
});
},
});
kendo.bind($("#whole"),model);
model.init();
Hopefully this will help you out with templating out the results.
https://dojo.telerik.com/ICOceLUj
In the example above I have created a custom column that takes the incoming row object and then parsed the name of the item and the category object into a single template.
To achieve this I have added the template property and used a function with an external template script to handle the manipulation. I personally find this easier to manage than trying to inline a complex client template (especially if you have logic involved)
So this is how we set it up initially:
{ title: "custom template", template:"#=customTemplate(data)#" }
obviously you will change it to the property you need to look at in your model.
then the function is a couple of lines of code:
function customTemplate(data){
var template = kendo.template($('#customTemplate').html());
var result = template(data);
return result;
}
so this takes the customTemplate template i have created for this and renders it as html and then it will apply the data where appropriate. The template looks like this:
<script id="customTemplate" type="text/x-kendo-template">
<div>
<h5> #:data.ProductName#</h5>
<h4>#: JSON.stringify(data.Category, null, 4) #</h4>
</div>
</script>
You can then customize this template to how you need it to look for your specific needs. You can then either create a source template for the items and then map the values back as single string or have the logic for this in the template. Which ever is most sensible in your case.
For more info on templating please look at this link:
https://docs.telerik.com/kendo-ui/framework/templates/overview
You can use kendo.stringify in your column template.
Example:
kendo.stringify(YourProperty)

Bind Kendo Grid data with dropdown value

I have kendo dropdownlist on page which is fetching results from database as below. I also have a grid at the same page at same time which needs kendo dropdownlist value i.e the value from years dropdownlist but I am unable to get it at the same time.This is how I am following. Where I am doing wrong.
<script type="text/javascript">
var GridUrl;
$("#Years").kendoDropDownList({
dataTextField: "Name",
dataValueField: "Id",
dataSource: {
transport: {
read: {
dataType: "json",
url: "../../Service/GetYears"
}
}
}
});
$(document).ready(function () {
BindGridData();
GridUrl = '#Url.Action("Read", "Home")';
});
function BindGridData()
{
GridDataSource = new kendo.data.DataSource({
type: "aspnetmvc-ajax",
serverFiltering: true,
serverPaging: true,
serverSorting: true,
pageSize: 10,
transport: {
read: {
url: GridUrl,
data: { year: $('#Years').val() }
}
},
schema: {
data: "Data", total: "Total"
}
});
}
Changing line to this
year: $('#Years').data("kendoDropDownList").value()
should do a trick. You need to get instance of kendoDropDownListwidget in order to get its value. You need to do so, because kendoDropDownListwidget value is not saved directly into html element
First of all, you need to move the initialisation of the kendoDropDownList inside the document ready function. If you don't you may end up refering to elements that are not loaded (yet).
The second change that should be done is how you get the value from the kendoDropDownList. Usually, you should refer to the widget instead of the DOM element: $('#Years').data("kendoDropDownList").value()
Finally, you didn't mention how and when your grid was binded but you may want to refresh the grid data if the user change the dropdown value. If it's the case, you may want to use change event of the dropdown to refresh the grid data.
$(document).ready(function () {
$("#Years").kendoDropDownList({
dataTextField: "Name",
dataValueField: "Id",
dataSource: {
transport: {
read: {
dataType: "json",
url: "../../Service/GetYears"
}
}
},
change: function(e) {
$("#YourGrid").data("kendoGrid").dataSource.read();
}
});
BindGridData();
GridUrl = '#Url.Action("Read", "Home")';
});
function BindGridData() {
GridDataSource = new kendo.data.DataSource({
type: "aspnetmvc-ajax",
serverFiltering: true,
serverPaging: true,
serverSorting: true,
pageSize: 10,
transport: {
read: {
url: GridUrl,
data: { year: $('#Years').data("kendoDropDownList").value() }
}
},
schema: {
data: "Data", total: "Total"
}
});
}

What is failing on my kendo cascading dropdownlist.Only works first time

So im currently using 2 dropdownlists where the second should get items from the server according to the selected item from the first one, the problem is that this only works the first timei click on the child droplist, which means if i change the parent list item the child one will still show the previous items.
Here's some code:
kendofi=function (index){
//kendofi select boxes
$("#dynamicFormLinha"+index).kendoDropDownList({
name:"formularios",
optionLabel: "Formulario",
dataTextField: "name",
dataValueField: "id",
dataSource: {
type: "json",
serverFiltering: true,
transport: {
read: "${pageContext.request.contextPath}" + "/newlayout/mySearchesDynForms.do"
},
schema: {
model: {
fields: {
id: { type: "number" },
name: { type: "string" }
}
}
}
}
}).data("kendoDropDownList");
$("#campoFormLinha"+index).kendoDropDownList({
autoBind:false,
name:"campos",
optionLabel: "Campo",
dataTextField: "name",
dataValueField: "id",
dataSource: {
type: "json",
serverFiltering:true,
transport: {
read:{
url:"${pageContext.request.contextPath}" + "/newlayout/mySearchesFormFieds.do",
data:function(){
return {formId: $("#dynamicFormLinha"+index).val()
};
}
}
}
},
cascadeFrom: "dynamicFormLinha1",
schema: {
model: {
fields: {
id: { type: "number" },
name: { type: "string" }
}
}
}
}).data("kendoDropDownList");
And here's the java spring controller class methods for each dropdownlist:
#RequestMapping(method = RequestMethod.GET, value="/newlayout/mySearchesDynForms")
public #ResponseBody
DynamicFormTemplateDPO[] getForms(){
return dynamicFormService.getAllActiveFormTemplatesForPresentation();
}
#RequestMapping(method = RequestMethod.GET, value="/newlayout/mySearchesFormFieds")
public #ResponseBody
DynamicFieldTemplateDPO[] getFormFields(#RequestParam long formId){
return dynamicFormService.getFormFields(formId);
}
These all return json data, the parent child returns this:
[{"id":1,"name":"drcie"},{"id":2,"name":"edp"},{"id":3,"name":"pt"}]
And the id selected is then used as the formId parameter in the getFormFields method, which returns something like this:
[{"id":1,"name":"Nome","type":"STRING"},{"id":2,"name":"Morada","type":"STRING"},{"id":3,"name":"Contribuinte","type":"STRING"},{"id":4,"name":"Multibanco","type":"STRING"}]
The kendofi method here is because these widgets are inside a table and you can add new table rows while maintaining the widgets functionality.
I had the same problem. We managed to solve this by putting the parent and children dropdownlists in one function. See buildLookupDropDownList() function below. Looks like in our situation the children dropdownlists were being called before the parent. Best of luck
var categories
function buildLookupDropDownList() {
categories = $("#LOOKUP_OBJECT_ID").kendoDropDownList({
optionLabel: "#Resources.Global.Builder_Parameter_SelLookup",
dataTextField: "OBJECT_NAME",
dataValueField: "OBJECT_ID",
dataSource: lookupDS,
}).data("kendoDropDownList");
var products = $("#DISPLAY_FIELD").kendoDropDownList({
autoBind: false,
cascadeFrom: "LOOKUP_OBJECT_ID",
optionLabel: "#Resources.Global.Builder_Parameter_SelDisplay",
dataTextField: "DISPLAY_LABEL",
dataValueField: "FIELD_NAME",
dataSource: {
serverFiltering: true,
transport: {
read:
{
url: '#Url.Action("GetFields", "Object")',
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: function () {
var lookuplist = $("#LOOKUP_OBJECT_ID").data("kendoDropDownList");
return { OBJECT_ID: lookuplist.value() };
}
}
},
schema: {
data: function (data) { //specify the array that contains the data
return data.data || data;
}
}
}
}).data("kendoDropDownList");
var orders = $("#VALUE_FIELD").kendoDropDownList({
autoBind: false,
cascadeFrom: "DISPLAY_FIELD",
optionLabel: "#Resources.Global.Builder_Parameter_SelValue",
dataTextField: "DISPLAY_LABEL",
dataValueField: "FIELD_NAME",
dataSource: {
serverFiltering: true,
transport: {
read:
{
url: '#Url.Action("GetFields", "Object")',
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: function () {
var lookuplist = $("#LOOKUP_OBJECT_ID").data("kendoDropDownList");
return { OBJECT_ID: lookuplist.value() };
}
}
},
schema: {
data: function (data) { //specify the array that contains the data
return data.data || data;
}
}
}
}).data("kendoDropDownList");
}

Resources