Kendo Grid - make a column always appear as dropdown boxes - javascript

I've got a Kendo grid which is being created in JS. This code is not mine, but someone else's, and I really don't think we should be changing many of the fundamentals of it. However, there is one column in it which we would ideally like to display as a dropdown box all the time, or at least look like one. Code is below:
self.caGridOptions = {
widget: self.caKendoGrid,
data: undefined,
dataSource: {
schema: {
model: {
fields: {
id: { type: "number" },
description: { type: "string", editable: false },
value: { type: "number", editable: false },
caTypeDescription: { type: "string", editable: false }
}
}
},
autoSync: true
},
sortable: true,
scrollable: false,
editable: true,
columns: [
{ field: "id", title: "Code", width: 90, template: "#=pager.activePage$().ctx.getca ? pager.activePage$().ctx.getca(id, 'code') : id #", editor: self.caDropDownEditor },
{ field: "description", title: "Description", width: 90, template: "#=pager.activePage$().ctx.getca ? pager.activePage$().ctx.getca(id, 'description') : id #" },
{ field: "value", title: "Value", width: 90, format: "{0:n2}", template: "#=pager.activePage$().ctx.getca ? pager.activePage$().ctx.getca(id, 'value') : id #" },
{ field: "caTypeDescription", title: "Type", width: 90, template: "#=pager.activePage$().ctx.getca ? pager.activePage$().ctx.getca(id, 'caTypeDescription') : id #" },
{ width: 90, filterable: false, template: kendo.template('<a class="btn btn-danger btn-sm" title="delete"><i class="fa fa-trash-o fa-fw" aria-hidden="true"></i> Delete</a>') }
],
dataBound: self.gridButtons,
noRecords: true,
messages: {
noRecords: "There is no data available"
}
};
//
// functions
self.getca = function (id, type) {
if (id == null) return null;
return self.caOptions().filter(function (item) { return item.id == id; })[0][type];
};
The ID field (first column) goes into a dropdown box when it is edited, as you can see. However, what we would like is for this to appear as a dropdown box all the time. Not necessarily by always having the editor on (which I believe would be impossible, as Kendo can only turn the editor on on one row at a time), but perhaps by simply formatting it like a dropdown.
Any help would be gratefully appreciated. It's annoying as this is a tiny, minor thing and we've got examples of it working elsewhere, but they're grids which have been written primarily in cshtml (using Kendo MVC, I think) and I really don't want to rewrite the entire grid for something so trivial, as well as possibly any other functions that rely on its data.

The primary issue you are facing is that the cell is just a table cell until you actually start editing. At that time, it dynamically creates the input.
I had a similar requirement in the past and it ended up being easier to decorate the cell to look like a drop-down as opposed to trying to render a drop-down in every row of the grid. This allows you to keep the default grid behavior intact and allows the user to see that there will be a list of values when they edit that cell. We ended up just putting a down-arrow icon to the right of the value in the display template - from your code, it looks like you are using some font-awesome icons, but there are some delivered by Kendo UI as well - so, the template could be something like this:
template: '#=id# <span class="k-icon k-icon-s"></span>'
UPDATE:
The kendo icons do depend on your version and I had a typo in the name above. In any case, here is an example you can look at:
This Kendo demo shows adding a custom editor (dropdown) on the Category column:
http://demos.telerik.com/kendo-ui/grid/editing-custom
If you scroll down, there is a button to "Edit this Example" - here, you'll see that the Category column uses a template:
template: "#=Category.CategoryName#"
You can change the template to the following to create a drop-down looking effect:
template: "<span style='border-style:solid; border-width: 1px; padding: 4px; width: 150px; display: block'>#=Category.CategoryName# <span class='k-icon k-i-arrow-60-down' style='float:right'></span></span>"
You can tune the css to get it closer to exactly what you want, but this give you the idea. Other possibilities include actually defining css classes that can be applied so you don't need to include so much in-line styling.

Related

Kendo ui remove number filter spinner

I have this filter field with arrows that increase or decrease numbers and I want to remove them
As far I've tried several solutions that didn't help
{
field: "TotalEnergyCharge",
title: "Calc Total",
format: "{0:n2}",
width: "70px",
headerAttributes: {
style: "overflow: visible; white-space: normal; text-align: center; font-weight: bold"
},
attributes: {
style: "text-align: right"
},
operator: "eq",
filterable: {
cell: {
operator: "eq",
showOperators: false
}
},
spinners: false,
editor: function (container, options) {
$('<input data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoNumericTextBox({
spinners: false
});
}
},
You couldn't remove because both ways you're trying are meant to work in a different way. The spinners before editor won't work at all, and the spinners option for the widget located inside editor will work only when user edits a row.
Now, for the filter widget, I couldn't find anything strightforward to use, like an event or method as used in editor. It seems that there is nothing like that for filters.
So I did a trick after grid initialization, changing the filters' fields options:
$('#grid .k-filter-row input[data-role="numerictextbox"]').each((i, el) => {
$(el).data('kendoNumericTextBox').setOptions({ spinners: false });
});
Dojo
Modify the selector to get the filters you like to remove the spinners.
Note that setOptions is not listed as a method in the NumericTextBox documentation. Kudos for Kendo!!

Disable movement of columns in agGrid

I'm using AgGrid table in my application. Here is the demo. According to the documentation i want to stop movement of the columns. For this i used:
suppressMovable: true
The above code I used here:
columnDefs: [
{
headerName: 'Athlete', //the generic name of header
children: [
{
field: 'athlete', //children header from generic header
width: 150,
suppressMovable:true
},
{
field: 'age',
lockVisible: true,
cellClass: 'locked-visible',
suppressMovable:true
},
{
field: 'country',
width: 150,
},
{ field: 'year' },
{ field: 'date' },
{ field: 'sport' },
],
...
suppressMovable:true, it works, and the athlete and age columns aren't possible to be moved like others, but this code also disable the movement of the main column: Athlete. So when i try to switch the place of Athlete and Medals columns, i can't, but i don't want this, i want to set this 2 main columns as movable.Question: How to disable movement of columns inside the Athlete and Column, but to keep the movement functionality of these 2 main columns?
Out of the box answer is you can't.
If any child is fixed, then AG Grid doesn't allow moving the group.
you can write custom event listener(if possible) to change the suppressMovable property of child columns while the parent column is being dragged and then again set them to not movable/suppressMovable to true. else you can programatically move all columns in a group using moveColumnByIndex(from,to)

How to expand a kendo grid on clicking a column value using angular js

I am trying to use Kendo UI Grid with angular js. I need to expand the grid to further level when user clicks a link given in one of the columns of the grid.
I used following code to expand the grid on click of an tag inside a kendo grid column.
$scope.mainGridOptions = {
dataSource: {
data: $scope.data,
schema: {
model: {
fields: {
fieldA: { type: "string" },
fieldB: { type: "string" },
fieldC: { type: "string" },
fieldT: { type: "numeric" }
}
}
},
pageSize: 10
},
filterable: true,
sortable: true,
resizable: true,
pageable: true,
scrollable: true,
columns: [
{ field: "fieldA", title: "FieldA", width: 90},
{ field: "fieldB", title: "FieldB", width: 90},
{ field: "fieldC", title: "FieldC", width: 90},
{ field: "fieldT", title: "FieldT", width: 90, template: "<a onclick='expand(this)'href='\\#'>#=mydata#</a>"}
]
};
But on running the code it just gives me an error in the browser console window.
Uncaught ReferenceError: expand is not defined at
HTMLAnchorElement.onclick
I researched and found that Kendo doesn't supports onclick event inside an tag. Therfore tried to use tag instead of tag. But it still does not work.
{ field: "fieldT", title: "FieldT", width: 90, template: "<span ng-click='showFileLevel(this)>{{mydata}}</span>"}
Can anyone please guide me in the right direction or let me know how can I expand a Kendo grid to further levels on clicking text inside a certain column of the grid using Angular JS.
you write expand(this) method out of the controller in your js.

Inline editing with conditionally disabled controls

I am using the Telerik Kendo UI grid. I have configured it to use grid inline editing. I have an interesting requirement. One of the columns is a checkbox and this defines whether some of the controls are editable or not. i.e when ticked columns E,F,G are read-only and others are editable. When unticked column B,C are editable and others are read-only.
I have successfully implemented this but I would like to improve it. I have implemented it so that the controls are disabled. However, I would prefer if it the controls change to labels such as the Display Mode.
function gridEdit(e) {
setRowStatus(e.container, e.model.IsCustomJob);
}
function setRowStatus(c, isSpecificSH) {
changeControlStatusNumeric(c, 'ColumnB', !IsCustomJob);
changeControlStatusNumeric(c, 'ColumnC', !IsCustomJob);
changeControlStatusNumeric(c, 'ColumnE', IsCustomJob);
changeControlStatusNumeric(c, 'ColumnF', IsCustomJob);
changeControlStatusDropDown(c, 'ColumnG', IsCustomJob);
}
function changeControlStatusNumeric(c, name, isEnabled) {
var ctrl = c.find("input[name='" + name + "']").data("kendoNumericTextBox");
ctrl.enable(isEnabled);
if (!isEnabled) {
ctrl.value('');
}
}
The problem with my implementation as can be seen below is that it is not very clear for the user which items are editable and which items are not. That is why I would like to change the disabled controls to labels or maybe hide them completely. Is there a functionality in the Grid API for implementing this ... or maybe I should implement this using jquery?
When Ticked:
When Unticked:
I'd suggest creating custom editors for the columns that should be disabled and then conditionally append read-only content instead of the editor, e.g. like this:
Grid:
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
height: 430,
toolbar: ["create"],
columns: [{
field: "ProductName",
title: "Product Name"
}, {
field: "Category",
title: "Category",
width: "160px",
editor: categoryDropDownEditor,
template: "#=Category.CategoryName#"
}, {
field: "UnitPrice",
title: "Unit Price",
format: "{0:c}",
width: "120px"
}, {
command: ["edit", "destroy"]
}],
editable: "inline"
});
Editor:
function categoryDropDownEditor(container, options) {
// if model is set to disabled we don't show an editor
if (options.model.disabled) {
$("<span>" + options.model.get(options.field).CategoryName + "</span>").appendTo(container);
return;
};
$('<input required data-text-field="CategoryName" data-value-field="CategoryID" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
autoBind: false,
dataSource: {
type: "odata",
transport: {
read: "http://demos.telerik.com/kendo-ui/service/Northwind.svc/Categories"
}
}
});
}
You could set the model.disabled property in your changeControlStatusNumeric function, or if you don't want an additional field in the model, you can add a CSS class to the container and check for that in the custom editor.
(demo)

Create another toolbar in kendo grid

I am using Kendo library for grid. I want to have a toolbar in that grid.
I have followed this link -
http://demos.kendoui.com/web/grid/toolbar-template.html
and created a toolbar at the top
I also want to add another toolbar at the bottom of grid. Below or above pagination bar. I could not find any way to create this extra toolbar. Please help.
There are two ways of getting it:
You let Kendo UI generate in the top and then you move it to the bottom
You generate it to the bottom.
The first approach is fast and if you don't need header toolbar is the best. Just add the following code:
$("#grid).data("kendoGrid").wrapper.append($(".k-toolbar"));
See it here : http://jsfiddle.net/OnaBai/WsRqP/1/
The second approach -using as base the example that you mention in your original question- would be something like this:
Step 1: Define a template, you might use the same than in the example:
<script type="text/x-kendo-template" id="template">
<div class="toolbar">
<label class="category-label" for="category">Show products by category:</label>
<input type="search" id="category" style="width: 150px"/>
</div>
</script>
Step 2: Initialize the grid, as you are doing now (in my case I will not include the toolbar as header but only as footer):
var grid = $("#grid").kendoGrid({
dataSource: {
type : "odata",
transport : {
read: "http://demos.kendoui.com/service/Northwind.svc/Products"
},
pageSize : 20,
serverPaging : true,
serverSorting : true,
serverFiltering: true
},
height : 430,
sortable : true,
pageable : true,
columns : [
{ field: "ProductID", title: "Product ID", width: 100 },
{ field: "ProductName", title: "Product Name" },
{ field: "UnitPrice", title: "Unit Price", width: 100 },
{ field: "QuantityPerUnit", title: "Quantity Per Unit" }
]
}).data("kendoGrid");
Step 3: Add a dataBound handler for creating the footer after the grid has been initialized. We have to do it on dataBound otherwise the Grid is still not correctly formatted and the footer will look wrong. I've implemented creating the footer toolbar in a separate function to do not mess dataBound in case you do more stuff here.
dataBound : function () {
initFooterToolbar(this, kendo.template($("#template").html()));
}
Step 4: Implement this initFooterToolbar:
function initFooterToolbar(grid, template) {
if (!this._footer) {
this._footer = $("<div class='k-toolbar k-grid-toolbar k-widget'></div>")
.append(template);
grid.wrapper.append(this._footer);
// Other code for initializing your template
...
}
}
What initFooterToolbar does is first check that it has not already been initialized otherwise if you do pagination of refresh the data you might end-up with multiple footer toolbars.
Finally append the toolbar to grid.wrapper.
So the important part for creating a footer toolbar is invoking grid.wrapper.append(...) and doing it when the grid is already created.
The original example modified here : http://jsfiddle.net/OnaBai/WsRqP/
I avoid using kendo toolbars and just make an external 1 which you can then tweak with greater control.
For example,
#Html.DropDownList("Year", (SelectList)ViewBag.YearList, "All years")
transport: {
read: {
url: '#Url.Action("_List", "Applications")',
data: refreshGridParams,
type: 'POST'
},
function refreshGridParams() {
return {
Year: $('#Year').val()
};
}
$('#Year').change(function () {
theGrid.dataSource.read({
Year: $('#Year').val()
});
});
Then in my controller,
[HttpPost]
public JsonResult _List(int? Year, int skip, int take)
{
Last
_db.Blargh.Where(w => w.Year== Year).Skip(skip).Take(take).ToList().ForEach(x => { waList.Add(new WAListDTO(x)); });
This should cover all the core code needed but means you can keep adding as many toolbars/dropdowns/datepickers/text searchs or etc and just alter each stage to include the additional data.
Here is another hack which uses column footertemplate. When databound is triggered, footertemplate table is arranged to have one column with colspan equals to the number of grid columns.
http://plnkr.co/edit/1BvMqSC7tTUEiuw4hWZp
$("#grid").kendoGrid({
columns:[{
field:'name',
footerTemplate : "Row Count: #= data.name.count #"
},{
field:'age'
}],
dataSource: new kendo.data.DataSource({
aggregate: [{
field:"name",
aggregate: "count"
}],
data: [{
name: "Jane",
age: 31
}, {
name: "John",
age: 33
}]
}),
dataBound: function() {
var footer = this.wrapper.find('.k-footer-template');
footer.children(":first").attr('colspan', this.columns.length);
footer.children().not(':first').remove();
}
});

Categories

Resources