How to filter dojo enhanced grid by external textbox - javascript

In my scenario, I am maintain a grid that need to be filter a particular column by the onchange event in a textbox. According to the text change grid should be filtered. I already able to use filter capability provided by the enhancedgrid and want to do it externally.
already imported 'dojox/grid/EnhancedGrid','dojo/data/ItemFileWriteStore', dojox/grid/enhanced/plugins/Pagination', 'dojox/grid/enhanced/plugins/Filter',
This is in the external js file. A.js
grid = new EnhancedGrid({
store: new ItemFileWriteStore({
data: gridObject
}),
// "username, firstName, lastName, email, userGroupName, lastLoginValue, phoneNo, organization, status"
structure: [
{
name: "User Login Name",
field: "username",
width: "84px"
},
{
name: "First Name",
field: "firstName",
width: "84px"
},
{
name: "Last Name",
field: "lastName",
width: "70px"
},
{
name: "Email",
field: "email",
width: "70px"
}
],
rowSelector: '20px',
minRowsPerPage: 5,
rowsPerPage: 5,
plugins: {
pagination: {
pageSizes: ["10", "25", "50", "100", "All"],
description: true,
sizeSwitch: true,
pageStepper: true,
gotoButton: true,
/*page step to be displayed*/
maxPageStep: 4,
/*position of the pagination bar*/
position: "bottom"
},
filter: {
closeFilterbarButton: false,
ruleCount: 2
//itemsName: "rows"
}
}
}, "gridee");
console.log(grid);
/*append the new grid to the div*/
grid.placeAt("gridView");
grid.startup();
--------------- function end ----------------
UsersCtrl.prototype.filterGrid = function () {
var filterText = document.getElementById("txtFilter").value, innerDiv = document.getElementById("gridView").firstChild.getAttribute("id");
// innerDiv gave the grid id to be filtered.
dijit.byId(innerDiv).filter("username", filterText);// Dont no this is correct or not.
};
-----------html file-----------------
Here angular and dojo both used. angular function also called successfully and able to get into the filterGrid function.
grid === UsersCtrl
<input type="search" placeholder="Filter by Keywords" data-column="all" data-ng- model="grid.searchText" data-ng-change="grid.filterGrid()" data-dojo-type="dijit/form/TextBox" id="txtFilter">
<div id="gridView" style="width:100%; height:300px" align="center" class="claro"></div>
I am getting this error TypeError: object is not a function. Please help to overcome this.

Gladly I was able to get an idea after referring this Set query to search all fields of a dojo datagrid
import dijit/registry
grid = registry.byId("grid");
if (filterText) {
grid.setQuery({"username": filterText + "*"});
} else {
grid.setQuery({"username": "*"});
}
//dijit.byId("grid").store.fetch(query: {username: filterText});

Related

Dynamically setting the sortable property of a kendo grid column

I'm trying to set a kendo grid column's sortable property via a variable to control when the column can have sorting facility and when it can't.
But this is not working.
If I directly set the sortable property to true/false it works accordingly, but when I'm using a variable to set it, it is not, regardless of the variable value, the property is always set to 'true'.
Example:
This works as expected.
<div id="grid"></div>
<script>
$("#grid").kendoGrid({
columns: [
{ sortable: false, field: "id" },
{ field: "name" }
],
sortable: true,
dataSource: [ { id: 1, name: "Jane Doe" }, { id: 2, name: "John Doe" } ]
});
</sript>
But this does not, id field always gets sortable property as true
<div id="grid"></div>
<script>
// if first time it's true, then the sortable property is retaining true always,
// regardless if on second call the variable is set to false. there is no effect
var setColumnSort = canBeFalseOrTrue;
$("#grid").kendoGrid({
columns: [
{ sortable: setColumnSort, field: "id" },
{ field: "name" }
],
sortable: true,
dataSource: [ { id: 1, name: "Jane Doe" }, { id: 2, name: "John Doe" } ]
});
</script>
Is there anyway to dynamically disable/enable sorting of a column in a kendo grid?
You need to set it dynamically through grid properties once the grid is initialized.
$('#grid').kendoGrid({
sortable: true,
columns: [
{...}
]
});
var grid = $('#grid').getKendoGrid();
var options = grid.options;
options.columns[0].sortable = false;
grid.setOptions(options);
Example: Enable/disable sorting on column

Kendo grid when create a new row, auto populate fields with values from existing row

I have 5 columns (kendo grid) that gets data from the database. What I'm trying to do is, whenever I add a new row, I want certain columns to be auto populated dynamically.
For example, I have Name, country, state, value, and effDate columns.
Name, country, state fields are editable = false. So users are only able to edit value and effDate fields.
If Name = John, Country = USA, State = Alaska, Value = 123, effDate = 9/11/2019 and when I add a new row, I want Name, country, state fields to be populated with Name - John, Country - USA, State - Alaska. Value and effDate should only be empty so that users can add new data.
I'm currently using template.
I tried this to populate country column, but it's not showing anything.
template: "#= Country #"
Is there a way to pre-populate dynamically when create a new row?
Part of my grid codes model:
{
id: "NameKey",
HouseKey: houseKey,
fields: {
Name: { editable: false },
Country: { editable: false },
State: { editable: false },
Value: {
validation: {
pattern: {
value: "^[0-9.]{0,10}$",
message: "Only numbers"
},
required: {
message: "Value is required"
},
}
},
EffDate: { validation: { required: true }, type: "date", format: "{0:MM/dd/yyyy}" },
},
...
part of the columns
columns: [
{ field: "Name", template: "#=(Name== '') ? 'Fields are auto populated' : Name#", title: "Name", width: 250 },
{ field: "Country", template: "#=(Country== '') ? 'Fields are auto populated' : Countr#", title: "Country", width: 210 },
{ field: "State", template: "#=(StateName == '') ? 'Fields are auto populated' : State#", title:"State", width: 200 },
{ field: "Value", title:"Value", width: 200 },
{
field: "EffDate", title;"Date", template: "#= kendo.toString(kendo.parseDate(data.EffDate, 'yyyy-MM-dd'), 'MM/dd/yyyy') #", width: 140
},
],
You can use the beforeEdit event to achieve that behaviour. That event is called whenever the user tries to edit or create a new entry in the grid. It receives the current model, which you can change according to your needs:
beforeEdit: function(e) {
let model = e.model;
if (model.isNew()) {
model.Name = "John";
model.Country = "USA";
model.State = "Alaska";
}
}
Demo

Kendo UI Grid - Binding to navigation properties

I am using the Kendo UI grid and am display a role of models. Each model has a navigation property, and I am trying to display a field that exists in this navigation property.
//schema for my kendo data source
schema: {
data: function (data) {
return data || [];
}
}
......................................................
$("#FAAFreqGrid").kendoGrid({
dataSource: FAADS,
columns: [
{ field: "Id", title: "Freq ID", format: "{0:c}", width: "120px" },
{ field: "Frequency", title: "Frequency Test" format: "{0:c}", width: "120px" },
{ field: "FREQ_POOL", title: "FAATEST", format: "{0:c}", width: "120px" },
{ command: ["edit", "destroy"], title: " ", width: "250px" }
],
toolbar: ["create"],
editable: "inline",
pageable: true
});
If I go to my Web API Url, I get a json response of:
[{"$id":"1","Frequency":"164.1375","FREQ_POOL":{"$id":"2","IsAM":true,......etc}
FREQ_POOL is my navigation property, and it has the data I want. Frequency exists and displays in my grid properly. But my FREQ_POOL field says [object Object], and if I try to say "FREQ_POOL.IsAM", it says IsAM is not defined. I cannot get it to bind to any property I can bind to any other non-navigation field. How do I make this work? The data exists in the JSON object that is returned, but the binding just isn't working correctly. Thanks.
You could set a template for the column in question, like this:
$("#grid").kendoGrid({
columns: [ {
field: "name",
template: "<strong>#: name.first#, #: name.last# </strong>"
}],
dataSource: [ { name: { first: 'Jane', last: 'Doe' } }, { name: { first: "John", last: 'Doe' } } ]
});
the template can then be used to show object in the dataset
more info, you could find here
For the editing, you could then also define the cell editor, with an extra template or function, more info about that, you could find here.

How can I set a max-width property to individual kendo grid columns?

Here's a jsfiddle with a sample kendo grid:
http://jsfiddle.net/owlstack/Sbb5Z/1619/
Here's where I set the kendo columns:
$(document).ready(function () {
var grid = $("#grid").kendoGrid({
dataSource: {
data: createRandomData(10),
schema: {
model: {
fields: {
FirstName: {
type: "string"
},
LastName: {
type: "string"
},
City: {
type: "string"
},
Title: {
type: "string"
},
BirthDate: {
type: "date"
},
Age: {
type: "number"
}
}
}
},
pageSize: 10
},
height: 500,
scrollable: true,
sortable: true,
selectable: true,
change: onChangeSelection,
filterable: true,
pageable: true,
columns: [{
field: "FirstName",
title: "First Name",
width: "100px",
}, {
field: "LastName",
title: "Last Name",
width: "100px",
}, {
field: "City",
width: "100px",
}, {
field: "Title",
width: "105px"
}, {
field: "BirthDate",
title: "Birth Date",
template: '#= kendo.toString(BirthDate,"MM/dd/yyyy") #',
width: "90px"
}, {
field: "Age",
width: "50px"
}]
}).data("kendoGrid");
applyTooltip();
});
I added individual widths to each of the columns. However, I would also like to set a max-width to each kendo grid column. Is it possible to set a max-width (not a set one for all columns but max-width for individual columns?)?
There is no property like max-width exposed for kendo grid. One of the round about solution will be to set Width of Column as autosize and then use template where you use css properties to maintain max width.
Following is the example. Not sure if you are looking for the same answer.
<style>.intro { max-width: 100px ;width: 20px ;background-color: yellow;</style>
<script>
$(document).ready(function () {
$("#grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read: "http://demos.telerik.com/kendo-ui/service/Northwind.svc/Customers"
},
pageSize: 20
},
height: 550,
groupable: true,
sortable: true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
columns: [{
field: "ContactName",
title: "Contact Name",
template : '<span class=intro>#:ContactName#</span>'
}, {
field: "ContactTitle",
title: "Contact Title"
}, {
field: "CompanyName",
title: "Company Name"
}, {
field: "Country",
width: 150
}]
});
});
</script>
I have JavaScript code that will help achieve this functionality. It provides a way for a (command) column to retain a fixed size.
On the one hand, it acts as a minimum size for a column, but if the grid were to increase in size, the original size is enforced. This allows for other grid cells to increase in size by a larger amount.
Check out this dojo that shows this code in action.
Note that all columns need to have a specified width (this effectively becomes a minimum width).
The browser resize event is used to trigger the size recalculation of the grids.
This function supports master/detail and grouping.
I have not considered column resizing at this point.
If you have any ideas for improvements then go for it!
.k-grid td
white-space: nowrap;
text-overflow: ellipsis;
max-width:150px;
}
YES....
You can set a textbox-style MAX WIDTH for column values in a Kendo Grid...and you can do a lot more too. However, you must do so by-hand using the grids Before Edit event.
FOR EXAMPLE:
// ELEMENTS
var $gridDiscipline = $('#gridDiscipline')
var grid = $gridDiscipline.kendoGrid();
// EVENTS
grid.bind('beforeEdit', beforeEdit);
// IMPLEMENTATION
function beforeEdit(e)
{
// Edit Master Row
// This event raises when ADD_NEW or EDIT is pressed
// Optionally, I add a slight timeout to ensure the MASTER ROW is "open"
// Obviously, the elements in your row will be different from mine
// As you will see...you can do all kinds of late-bound configuration practices here (whatever makes sense for you)
setTimeout(function () {
var $container = $('.k-master-row', e.sender.tbody);
// Elements
var $cmbContactEmployee = $container.find("#EmployeeId");
var $txtDisciplineName = $container.find("#DisciplineName");
var $txtTags = $container.find("#Tags");
// Instances
var cmbContactEmployee = $cmbContactEmployee.data('kendoComboBox');
// Configuration
cmbContactEmployee.dataSource.transport.options.read.data = function (e) {
var text = e.filter.filters[0].value;
return { searchText: text };
};
// If a DataAnnotation value exists...you can enforce it
var maxlength = $txtDisciplineName.attr('data-val-length-max');
if (maxlength) {
$txtDisciplineName.attr('maxlength', maxlength);
}
// Or you can set something outright
$txtTags.attr('maxlength', 100);
}, 500);
}

How Can I Hide Kendo UI Grid Columns using JavaScript, React, Angular, Vue or ASP.NET MVC

I'm working on a HTML5 and JavaScript website.
Is it possible to have a hidden column in Kendo UI Grid and access the value using JQuery?
Using JavaScript
See the Kendo UI API reference.
Hide a column during grid definition
You can add hidden: true:
$("#gridName").kendoGrid({
columns: [
{ hidden: true, field: "id" },
{ field: "name" }
],
dataSource: [ { id: 1, name: "Jane Doe" }, { id: 2, name: "John Doe" } ]
});
Hide a column by css selector
$("#gridName").find("table th").eq(1).hide();
Hide a column by column index
var grid = $("#gridName").data("kendoGrid");
grid.hideColumn(1);
Hide a column by column name
var grid = $("#gridName").data("kendoGrid");
grid.hideColumn("Name");
Hide a column by column object reference
var grid = $("#gridName").data("kendoGrid");
grid.hideColumn(grid.columns[0].columns[1]);
Using React
See the Kendo UI for React API reference
Hide a column during grid definition
You can set show: false:
class App extends React.Component {
columns = [
{
title: 'Product Id',
field: 'ProductID',
show: false
},
{
title: 'Product Name',
field: 'ProductName',
show: true
},
{
title: 'Unit Price',
field: 'UnitPrice',
show: true
}
]
constructor() {
super();
this.state = {
columns: this.columns,
show:false
};
}
render() {
return (
<div>
<Grid data={products} >
{this.state.columns.map((column, idx) =>
column.show && (<Column key={idx} field={column.field} title={column.title} />)
)}
</Grid>
</div>
);
}
}
Using Angular
See the Kendo UI for Angular API reference
Hide a column during grid definition
You can add [hidden]="true"
#Component({
selector: 'my-app',
template: `
<kendo-grid [data]="gridData" [scrollable]="scrollable" style="height: 200px">
<kendo-grid-column [hidden]="true" field="ID" width="120">
</kendo-grid-column>
<kendo-grid-column field="ProductName" title="Product Name" width="200">
</kendo-grid-column>
<kendo-grid-column field="UnitPrice" title="Unit Price" width="230">
</kendo-grid-column>
</kendo-grid>
`
})
Programmatically hide a column
#Component({
selector: 'my-app',
template: `
<div class="example-config">
<button (click)="restoreColumns()" class="k-button">Restore hidden columns</button>
</div>
<kendo-grid [data]="gridData" style="height:400px">
<ng-template ngFor [ngForOf]="columns" let-column>
<kendo-grid-column field="{{column}}" [hidden]="hiddenColumns.indexOf(column) > -1" >
<ng-template kendoGridHeaderTemplate let-dataItem>
{{dataItem.field}}
<button (click)="hideColumn(dataItem.field)" class="k-button k-primary" style="float: right;">
Hide
</button>
</ng-template>
</kendo-grid-column>
</ng-template>
</kendo-grid>
`
})
export class AppComponent {
public gridData: any[] = sampleCustomers;
public columns: string[] = [ 'CompanyName', 'ContactName', 'ContactTitle' ];
public hiddenColumns: string[] = [];
public restoreColumns(): void {
this.hiddenColumns = [];
}
public hideColumn(field: string): void {
this.hiddenColumns.push(field);
}
}
Using Vue
See the Kendo UI for Vue API reference
Hide a column during grid definition
You can add :hidden="true"
<kendo-grid :height="600"
:data-source-ref="'datasource1'"
:pageable='true'>
<kendo-grid-column field="ProductID" :hidden="true"></kendo-grid-column>
<kendo-grid-column field="ProductName"></kendo-grid-column>
<kendo-grid-column field="UnitPrice" title="Unit Price" :width="120" :format="'{0:c}'"></kendo-grid-column>
<kendo-grid-column field="UnitsInStock" title="Units In Stock" :width="120"></kendo-grid-column>
</kendo-grid>
Using ASP.NET MVC
See the Kendo MVC API reference
Hide a column during grid definition
#(Html.Kendo().Grid<Something>()
.Name("GridName")
.Columns(columns =>
{
columns.Bound(m => m.Id).Hidden()
columns.Bound(m => m.Name)
})
)
Using PHP
See the Kendo UI for PHP API reference
Hide a column during grid definition
<?php
$column = new \Kendo\UI\GridColumn();
$column->hidden(true);
?>
As #Nic says there are multiple ways of hiding a column but I'm gonna assume that you are using KendoUI methods for hiding it. I.e: set the column hidden to true or programmatically invoke hideColumn.
If so, you should remember that you model might have fields that are not displayed or not even mapped in columns but they exist and you can still access them.
If we have the following Grid definition:
var grid = $("#grid").kendoGrid({
dataSource: ds,
selectable: true,
...
columns :
[
{ field: "Id", hidden: true },
{ field: "FirstName", width: 90, title: "First Name" },
{ field: "LastName", width: 200, title: "Last Name" }
]
}).data("kendoGrid");
Where I've declared a column Id as hidden. I still can access the value of Id by going to the model using:
// I want to access the Id for row 3
var row = $("tr:eq(3)", "#grid");
// Retrieve the item from the grid using dataItem method
var item = $("#grid").data("kendoGrid").dataItem(row);
// Show Id
alert("Id is " + item.Id);
Runnable example
var grid = $("#grid").kendoGrid({
dataSource: [
{ Id: 1, FirstName: "John", LastName: "Smith" },
{ Id: 2, FirstName: "Jane", LastName: "Smith" },
{ Id: 3, FirstName: "Jack", LastName: "Smith" },
{ Id: 4, FirstName: "Joseph", LastName: "Smith" },
{ Id: 5, FirstName: "Jeff", LastName: "Smith" },
],
selectable: true,
columns :
[
{ field: "Id", hidden: true },
{ field: "FirstName", width: 90, title: "First Name" },
{ field: "LastName", width: 200, title: "Last Name" }
]
}).data("kendoGrid");
$("#show").on("click", function(e) {
var row = grid.select();
if (row) {
var item = grid.dataItem(row);
alert ("The ID is :" + item.Id);
} else { 
alert("Select a row");
}
});
#grid {
width : 490px;
}
<link href="http://cdn.kendostatic.com/2014.2.903/styles/kendo.common.min.css" rel="stylesheet" />
<link href="http://cdn.kendostatic.com/2014.2.903/styles/kendo.default.min.css" rel="stylesheet" />
<script src="http://cdn.kendostatic.com/2014.2.903/js/jquery.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.2.903/js/kendo.all.min.js"></script>
Select row and click <button id="show" class="k-button">Here</button> to show hidden Id.
<div id="grid"></div>

Categories

Resources