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

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>

Related

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

How to validate row selection in react ag-grid?

<div style={containerStyle} className="ag-theme-material">
<AgGridReact
columnDefs={this.state.columnDefs}
rowSelection={this.state.rowSelection}
onSelectionChanged={this.onSelectionChanged.bind(this)}
onGridReady={this.onGridReady.bind(this)}
groupSelectsChildren={true}
suppressRowClickSelection={true}
rowData={[{payment_date: 'jan', status: '100'}, {payment_date: 'feb', status: '200'}, {payment_date: 'mar', status: '300'}]}
>
</AgGridReact>
</div>
onSelectionChanged() {
var selectedRows = this.gridApi.getSelectedRows();
let paymentsrequest = [];
selectedRows.forEach(function(selectedRow, index) {
let paymentslistobject = {
'payment_date': selectedRow["payment_date"],
'status': selectedRow["status"]
};
paymentsrequest.push(paymentslistobject);
});
this.setState({
paymentsrequest
});
}
this.state = {
rowSelection: "multiple",
columnDefs: [
{
headerName: "Amount",
field: "status",
width: 250
},{
headerName: "Pay",
field: "",
checkboxSelection: true,
width: 100
},{
headerName: 'Payment Date',
field: 'payment_date',
width: 250
},
],
}
I am using react ag-grid component, I am using checkboxSelection for one of the column using checkboxSelection: true
I have check boxs for all the rows but once first row is checked only then he should be able to check second row till the time we should disable the checkboxes untill he checks first checkbox.
How to validate in columDefs as i was using checkboxSelection: true, How can I validate.
I checked all the documents for this but I didnot found any document

Using a directive multiple times containing kendo elements

I have the following directive
angular.module("KendoDemos", [ "kendo.directives" ])
.directive('myDirective',function(){
return{
template:'<div k-on-resize="resized()" kendo-splitter k-orientation="horizontal"id="splitter"><div><div kendo-grid="myGrid" options="mainGridOptions"></div></div><div><p>{{hello}}</p></div></div></div></div>',
scope:{},
controller:function($scope,$element){
$scope.hello = "Hello from Controller!";
$scope.mainGridOptions = {
dataSource: {
type: "odata",
transport: {
read: "http://demos.telerik.com/kendo-ui/service/Northwind.svc/Customers"
}
},
columns: [{
template: "<div class='customer-photo'" +
"style='background-image: url(../content/web/Customers/#:data.CustomerID#.jpg);'></div>" +
"<div class='customer-name'>#: ContactName #</div>",
field: "ContactName",
title: "Contact Name",
}, {
field: "ContactTitle",
title: "Contact Title"
}, {
field: "CompanyName",
title: "Company Name"
}, {
field: "Country",
}]
};
$scope.resized = function(){
if($("#splitter .k-pane:first").css("width") < '350px'){
$scope.myGrid.hideColumn("ContactName");
$scope.myGrid.hideColumn("Country");
}else{
$scope.myGrid.showColumn("ContactName");
$scope.myGrid.showColumn("Country");
}
};
}
}
})
Basically just creating a kendo Grid with some data and using a kendo splitter, the grid comes on the left side of the splitter. I have attached a event on kendo splitter where if the width is < 300px the grid will hide some columns.
This directive works perfectly if placed used only once on the a page but will not work if used multiple times. How to resolve this ??

How to filter dojo enhanced grid by external textbox

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});

Selecting rows from one grid & passing them to another grid

I'm trying to allow rows to be selected via checkboxes and for those selected rows and their IDs to be sent to another grid when a 'Submit' button is clicked. In other words, acting as some sort of filter.
I've contacted Telerik's support team and was advised to take the following steps in order to get it working:
Get the selected rows with the Select() method of the Grid
Loop through them & get the underlying item with the dataItem method
Save them into an array
Destroy the grid
Initialize a new grid by setting the data data
Here's a sample on JSBin that shows what I have in mind.
I'm not sure where to start honestly. I would really appreciate it if someone could point me in the right direction to any resources or guides that would be helpful. Thanks!
Assuming you are using RadGrid, make sure you have client side selection turned on, you would see something like this:
<ClientSettings>
<Selecting AllowRowSelect="True" />
<ClientEvents OnRowSelected="RowSelected" />
</ClientSettings>
On the input button, make sure to call your JS method as follows :
<input onclick="GetSelected();" .... >
Your JS code might look something like this :
function GetSelected() {
var grid = $find("<%=Your Grid's ClientID Here%>");
var MasterTable = grid.get_masterTableView();
var selectedRows = MasterTable.get_selectedItems(); // 1. Get the selected rows. The selected item can be accessed by calling the get_selectedItems() method of the GridTableView client-side object.
for (var i = 0; i < selectedRows.length; i++) {
var row = selectedRows[i];
// This is where you would have to insert it in a collection so that you can bind it to another grid... You will need to call .Rebind() once you assign the new datasource to the other grid.
}
Hopefully this will give you some idea.. I can see if I can find any examples on inserting rows into other grid if you get stuck.
check this code
html
<div id="grid1"></div>
<input type="button" value="Submit" onclick="Move()" />
<div id="grid2" ></div>
script
<script>
$(document).ready(function() {
var data1 = [
{ id: 1, rating: 3, year: 1997, title: "Rock" }
, { id: 2, rating: 5, year: 1999, title: "X-Man" }
, { id: 3, rating: 4, year: 2011, title: "World War Z" }
];
var grid1=$("#grid1").kendoGrid({
sortable: true
, silectable: true
, selectable: "multiple row"
, filterable: true
, pageable: true
, columns: [
{ template: "<input type='checkbox' class='checkbox' />", width: "40px" }
,{ field: "id", title: "Id", filterable: false }
, { field: "rating", title: "Rating", filterable: false }
, { field: "year", title: "Year", filterable: true, type: "string"}
, { field: "title", title: "Title" }
]
, dataSource: { page: 1,
pageSize: 5,
data: data1
}
}).data("kendoGrid");
grid1.table.on("click", ".checkbox", selectRow);
var data2 = [
{ id: 101, rating: 6, year: 2012, title: "The Impossible" }
, { id: 102, rating: 8, year: 2013, title: "Escape" }
, { id: 103, rating: 7, year: 2013, title: "Gravity" }
];
$("#grid2").kendoGrid({
sortable: true
, silectable: true
, selectable: "multiple row"
, filterable: true
, pageable: true
, columns: [
{ field: "id", title: "Id", filterable: false }
, { field: "rating", title: "Rating", filterable: false }
, { field: "year", title: "Year", filterable: true, type: "string"}
, { field: "title", title: "Title" }
]
, dataSource: { page: 1,
pageSize: 5,
data: data2
}
});
});
function Move() {
var grid1 = $("#grid1").data("kendoGrid");
var rows = grid1.select();
rows.each(function(index, row) {
var selectedRow = grid1.dataItem(row);
//-move to grid2
var grid2 = $("#grid2").data("kendoGrid");
var ins = { id: selectedRow.id, rating: selectedRow.rating, year: selectedRow.year, title: selectedRow.title }; //id=1,rating=9.2,year=1995,title="The Godfather"
grid2.dataSource.insert(ins);
});
rows.each(function() {
grid1.removeRow($(this).closest('tr'));
});
}
function selectRow() {
var checked = this.checked,
row = $(this).closest("tr");
if (checked) {
//-select the row
row.addClass("k-state-selected");
} else {
//-remove selection
row.removeClass("k-state-selected");
}
}
</script>
this will help you :)

Categories

Resources