Below is my code and currently for column titles I've hard-coded the weekdays. But I need to make it dynamic and display the titles as per the date changes. How can I display the js variable 'weekdate' as the title for each column? Any help would be appreciated. Thank you!
$("#grid-report-store").kendoGrid({
noRecords: true,
dataSource: grid_data_source_store(weekstart,weekend),
sortable: true,
resizable: true,
filterable: true,
columns: [
{ field: "EmployeeId", title: "Employee Id", width: 100},
{ field: "EmployeeName", title: "Employee Name", width: 100},
{ title: "Sunday", width: 120, filterable:false, template: function(dataItem) {
var weekdate = 'Day'+moment(weekstart).add(0, 'days').format('YYYYMMDD');
return (dataItem[weekdate])?dataItem[weekdate]:'';
}},
{ title: "Monday", width: 120, filterable:false, template: function(dataItem) {
var weekdate = 'Day'+moment(weekstart).add(1, 'days').format('YYYYMMDD');
return (dataItem[weekdate])?dataItem[weekdate]:'';
}},
{ title: "Tuesday", width: 120, filterable:false, template: function(dataItem) {
var weekdate = 'Day'+moment(weekstart).add(2, 'days').format('YYYYMMDD');
return (dataItem[weekdate])?dataItem[weekdate]:'';
}},
{ title: "Wednesday", width: 120, filterable:false, template: function(dataItem) {
var weekdate = 'Day'+moment(weekstart).add(3, 'days').format('YYYYMMDD');
return (dataItem[weekdate])?dataItem[weekdate]:'';
}},
{ title: "Thursday", width: 120, filterable:false, template: function(dataItem) {
var weekdate = 'Day'+moment(weekstart).add(4, 'days').format('YYYYMMDD');
return (dataItem[weekdate])?dataItem[weekdate]:'';
}},
{ title: "Friday", width: 120, filterable:false, template: function(dataItem) {
var weekdate = 'Day'+moment(weekstart).add(5, 'days').format('YYYYMMDD');
return (dataItem[weekdate])?dataItem[weekdate]:'';
}},
{ title: "Saturday", width: 120, filterable:false, template: function(dataItem) {
var weekdate = 'Day'+moment(weekstart).add(6, 'days').format('YYYYMMDD');
return (dataItem[weekdate])?dataItem[weekdate]:'';
}},
{ field: "TotalHours", title: "Total Hours", width: 100},
{ field: "OTHours", title: "O/T Hours", width: 100},
],
dataBound: function(e) {
$(".k-group-footer").css("text-align", "right" );
$(".w").addClass("btn btn-success" );
$(".d").addClass("btn btn-danger" );
$(".p").addClass("btn btn-warning" );
$(".u").addClass("btn btn-warning" );
$(".w-o").addClass("btn btn-warning" );
kendo.ui.progress($("#grid-report-store").css('padding', '0'), false);
}
});
You can do the following:
Get the fields from the grid's datasource's options's schema's model
Map the array to your desired format (e.g. field, title, filterable, template)
Set the columns property of the grid
Take a look at this example:
var dataSource = grid_data_source_store(weekstart,weekend)
var columns = Object
.keys(dataSource.options.schema.model.fields)
.filter(function(field) {
return field !== 'EmployeeId' && field !== 'EmployeeName' && field !== 'TotalHours' && field !== 'OTHours';
})
.map(function(field) {
return {
field: field,
title: field,
width: 120,
filterable: false,
template: function(dataItem) {
var weekdate = 'Day' + moment(weekstart).add(0, 'days').format('YYYYMMDD');
return (dataItem[weekdate])?dataItem[weekdate]:'';
}
}
});
columns.unshift({ field: 'EmployeeId', title: 'Employee Id', width: 100 });
columns.unshift({ field: 'EmployeeName', title: 'Employee Name', width: 100 });
columns.push({ field: 'TotalHours', title: 'Total Hours', width: 100 });
columns.push({ field: 'OTHours', title: '"O/T Hours', width: 100 });
$("#grid-report-store").kendoGrid({
noRecords: true,
dataSource: dataSource,
sortable: true,
resizable: true,
filterable: true,
columns: columns,
dataBound: function(e) {
$(".k-group-footer").css("text-align", "right" );
$(".w").addClass("btn btn-success" );
$(".d").addClass("btn btn-danger" );
$(".p").addClass("btn btn-warning" );
$(".u").addClass("btn btn-warning" );
$(".w-o").addClass("btn btn-warning" );
kendo.ui.progress($("#grid-report-store").css('padding', '0'), false);
}
});
Related
I have a Kendo Master/Detail grid (jquery) that expands all rows to reveal any child records upon page load to provide a grid with a set of default data. However, not all of the rows returned when expanded have child elements to display. I currently have a link provided in a column of the master row, the link is coded using a template:
{
template: `"<a class='_kwJISSearch' style='color:blue; text-decoration:underline; cursor: pointer;'>Edit Case Assignment</a>",`
width: "100px"
}
What I would like to know if I can change the text and what the link is pointing to on the master row if no child elements are returned? I have provided my code below, where I create the columns for the master first, then create the grid with a data-bound, lastly, I coded the detail:
function loadSearchGrid() {
searchOriginalColumnList = [
{
field: "CaseYear",
title: "Case Year",
type: "number",
width: "100px"
},
{
field: "CaseNumber",
title: "Case Number",
width: "100px"
},
{
field: "Full_Style",
title: "Style",
template: "<a href='/Cases/Views/CaseItems/ViewDocket?cy=#=CaseYear#&cn=#=CaseNumber#' target='_blank' style='color: blue; text-decoration:underline' ># if(Full_Style == null || Full_Style == '' ) {# N/A #} else{ # #:Full_Style# #} # </a>",
width: "250px"
},
{
field: "DispInfo",
title: "Disp Info",
width: "175px"
},
{
field: "Max_OA",
title: "OA Date",
format: "{0:MM/dd/yyyy}",
width: "100px"
},
{
field: "Max_Conf",
title: "Conf Date",
format: "{0:MM/dd/yyyy}",
width: "120px"
},
{
field: "Evote_Info",
title: "Evote",
template: "<a href=" + apiUrl +"JISReports/JIS_eVOTE&P_CASEYEAR=#=CaseYear#&P_CASENUMBER=#=CaseNumber#&rs:Command=Render' target='_blank' style='color:blue; text-decoration:underline; cursor: pointer;' ># if(Evote_Info == 'TRUE') {# Evote Info #} else{ # #} # </a>",
width: "100px"
},
{
field: "Ap_T_Related",
title: "Related Case",
//format: "{0:MM/dd/yyyy}",
width: "120px"
},
{
field: "Lead",
title: "Lead",
//format: "{0:MM/dd/yyyy}",
width: "100px"
},
{
field: "Not_Lead",
title: "Not Lead",
//format: "{0:MM/dd/yyyy}",
width: "100px"
},
{
//field: "Ap_T_Related",
//title: "Related Case",
//format: "{0:MM/dd/yyyy}",
template: /*"# if( getDetailGrids() == null ) {# Case Not Assigned #} else{# <a class='_kwJISSearch' style='color:blue; text-decoration:underline; cursor: pointer;'>Edit Case Assignment</a>#}#",//*/"<a class='_kwJISSearch' style='color:blue; text-decoration:underline; cursor: pointer;'>Edit Case Assignment</a>",
width: "100px"
},
];
var searchGridSavedColumns = utils.getGridSavedColumns(searchOriginalColumnList, config.gridSettingsKeys.jisSearch);
grid = $("#grid").kendoGrid({
dataSource: new kendo.data.DataSource({
transport: {
read: {
url: localRoutes.searchUrl,
dataType: "json",
method: "POST",
data: function () {
model = {
PanelType: viewModel.get("selectedPanelType"),
DispFinalInfo: viewModel.get("selectedFinalDisp"),
AssgnComp: viewModel.get("selectedAssignComp"),
ShowComm: viewModel.get("selectedShowComm"),
SortResult: viewModel.get("selectedSortResult"),
Assignment_Select: viewModel.get("selectedAssgnTypes"),
Assignment_For: viewModel.get("selectedSuiteMate"),
SearchCY: viewModel.get("caseYear"),
SearchCN: $('#caseNumber').val(),
Style: viewModel.get("style"),
};
return model;
}
}
},
error: function (e) {
$.unblockUI();
},
pageSize: 50,
schema: {
model: {
id: "CaseUaId",
fields: {
CaseUaId: { type: "string" },
PanelTypes: { type: "string" },
FinalDisp: { type: "string" },
AssignComp: { type: "string" },
ShowComm: { type: "string" },
SortResult: { type: "string" }
}
},
},
}),
pageable: {
refresh: true,
pageSizes: [20, 50, 100, 500]
},
toolbar: ["excel"],
editable: false,
groupable: true,
selectable: true,
filterable: true,
columnMenu: true,
scrollable: true,
reorderable: true,
resizable: true,//setting to allow column headers to be resizeable
autoBind: false,
sortable: {
mode: "multiple",
allowUnsort: true
},
toolbar: kendo.template($("#toolbar").html()),
excel: {
fileName: "JIS Search.xlsx",
allPages: true
},
//Second set of code for Master Detail
detailInit: detailInit,
dataBound: function (e) {
this.expandRow(this.tbody.find("tr.k-master-row"));//.first());
},
columns: (!!searchGridSavedColumns) ? searchGridSavedColumns : searchOriginalColumnList,
}).data("kendoGrid");
///Code to set the column headers as tooltips
grid.thead.kendoTooltip({
filter: "th",
content: function (e) {
var target = e.target;
return $(target).text();
}
});
$("#grid").on("click", "._kwJISSearch", function (e) {
e.preventDefault();
var ca = grid.dataItem($(e.currentTarget).closest("tr"));
var win = $("#_kwJISSearch").data("kendoWindow");
win.title();
win.content("");
win.refresh("/JIS/JISAssignment" +
"?cy=" + ca.CaseYear +
"&cn=" + ca.CaseNumber);
win.center().open().maximize();
});
searchGridSettingsViewModel = utils.createGridSettingsVM("Search Grid Settings", "grid", config.gridSettingsKeys.jisSearch, "gridSettingsTmpl", "gridSettingsDialog", true, true, true, true, 20);
kendo.bind($("#grid").find(".k-grid-toolbar"), searchGridSettingsViewModel);
searchGridLoaded = true;
}//end assignment grid creation
function detailInit(e) {
$("<div/>").appendTo(e.detailCell).kendoGrid({
dataSource: {
//type: "odata",
transport: {
read: {
url: localRoutes.searchAssgnUrl,
dataType: "json",
method: "POST",
data: {
cy: e.data.CaseYear,
cn: e.data.CaseNumber,
showHis: viewModel.get("selectedAssignComp"),
caseY: viewModel.get("caseYear"),
caseN: viewModel.get("caseNumber")
}
}
},
serverPaging: true,
serverSorting: true,
serverFiltering: true,
pageSize: 10,
filter: { field: "Case_Ua_Id", operator: "eq", value: e.data.CaseUaId }
},
scrollable: false,
sortable: true,
pageable: true,
columns: [
//{ field: "CaseUaId", width: "110px" },
{
field: "UserName", title: "User Name",
template: "# if(AssignEndDate == 'Incomplete' ) {# <span style='color:red; font-weight: bold'> #:UserName# </span> #} else{ # #:UserName# #} # ",
width: "70px"
},
{
field: "ReasonDesc", title: "Reason Desc",
template: "# if(ReasonDesc == 'EXPEDITED' || ReasonDesc == 'WALK' ) {# <span style='color:red; font-weight: bold'> #:ReasonDesc# </span> #} else{ # #:ReasonDesc# #} # ",
width: "70px"
},
{ field: "AssignBeginDate", title: "Begin Date", width: "70px" },
{
field: "AssignEndDate", title: "End Date",
template: "# if(Status_Code == 'PENDINGREVIEW' ) {# #:AssignEndDate# <span style='color:blue; font-style: italic'> (Pending Review) </span> #} else{ # #:AssignEndDate# #} # ",
width: "70px"
},
{ field: "DueDate", title: "Due Date", width: "70px" },
{ field: "AssignForLocID", title: "Assignment For", width: "100px" },
{ field: "AssignedByLocID", title: "Assigned By", width: "100px" },
{ field: "Comments", title: "Comments", width: "110px" },
]
});
}//end Case Assignment Detail Grid
You can use JavaScript code inside a template, e.g.:
template: "<a class='_kwJISSearch' style='color:blue; text-decoration:underline; cursor: pointer;'># if (data.childrenProperty && data.childrenProperty.length) { ##Edit Case Assignment## } else { ##No children text here ## } #</a>",
Assuming your master row has an array property for children.
I'm using Metronic Datatable and I want to hide some ID columns. How can I do it?
Here is my datatable initialization script and I want to hide 'site_id', 'kazan_id', 'boyler_id' columns. I tried the columnDefs option but it didn't work.
$('#tbl-boiler').mDatatable({
data: {
type: 'remote',
source: {
read: {
url: '/Company/GetBoilers/' + siteId,
}
},
},
sortable: false,
pagination: false,
rows: { autoHide: true },
columnDefs:[
{
targets: 0,
visible: false
}
],
columns: [
{
field: 'site_id',
title: 'site_id',
width: 100
},
{
field: 'kazan_id',
title: 'kazan_id',
width: 100
},
{
field: 'boyler_id',
title: 'boyler_id',
width: 100
},
{
field: 'okuma_ucreti',
title: 'Okuma Ücreti',
width: 100
},
{
field: 'kazan_no',
title: 'Kazan Numarası',
width: 120
},
{
field: 'kazan_sayac_no',
title: 'Kazan Sayaç Numarası',
width: 165
},
{
field: 'boyler_no',
title: 'Boyler Numarası',
width: 120
},
{
field: 'boyler_sayac_no',
title: 'Boyler Sayaç Numarası',
width: 170
},
{
field: 'blok_sayisi',
title: 'Bloklar',
width: 250
},
{
field: 'daire_sayisi',
title: 'Daireler',
width: 250
},
{
field: 'sayac_sayisi',
title: 'Sayaclar',
width: 250
},
{
field: 'actions',
title: 'İşlemler',
sortable: !1,
overflow: 'visible',
template: function (t) {
return '<a data-toggle="modal" data-target="#siteform" onclick="getBoiler(' + t.kazan_id + ');" class="edit-site m-portlet__nav-link btn m-btn m-btn--hover-accent m-btn--icon m-btn--icon-only m-btn--pill" title="Kazan Bilgilerini Düzenle">' +
'<i class="la la-edit"></i>' +
'</a>' +
'<a onclick="deleteBoiler(' + t.kazan_id + ')" class="m-portlet__nav-link btn m-btn m-btn--hover-danger m-btn--icon m-btn--icon-only m-btn--pill" title="Kazanı Sil">' +
'<i class="la la-trash"></i>' +
'</a>';
},
width: 250
}
]
});
Metronic uses jquery datatables plugin which can be found here.
Just changing the columns you want to hide to the following code should work.
I have just added visible: false to columns. You can remove columnDefs after making this change.
$('#tbl-boiler').mDatatable({
data: {
type: 'remote',
source: {
read: {
url: '/Company/GetBoilers/' + siteId,
}
},
},
sortable: false,
pagination: false,
rows: { autoHide: true },
columns: [
{
field: 'site_id',
title: 'site_id',
visible: false
},
{
field: 'kazan_id',
title: 'kazan_id',
visible: false
},
{
field: 'boyler_id',
title: 'boyler_id',
visible: false
},
{
field: 'okuma_ucreti',
title: 'Okuma Ücreti',
width: 100
},
{
field: 'kazan_no',
title: 'Kazan Numarası',
width: 120
},
{
field: 'kazan_sayac_no',
title: 'Kazan Sayaç Numarası',
width: 165
},
{
field: 'boyler_no',
title: 'Boyler Numarası',
width: 120
},
{
field: 'boyler_sayac_no',
title: 'Boyler Sayaç Numarası',
width: 170
},
{
field: 'blok_sayisi',
title: 'Bloklar',
width: 250
},
{
field: 'daire_sayisi',
title: 'Daireler',
width: 250
},
{
field: 'sayac_sayisi',
title: 'Sayaclar',
width: 250
},
{
field: 'actions',
title: 'İşlemler',
sortable: !1,
overflow: 'visible',
template: function (t) {
return '<a data-toggle="modal" data-target="#siteform" onclick="getBoiler(' + t.kazan_id + ');" class="edit-site m-portlet__nav-link btn m-btn m-btn--hover-accent m-btn--icon m-btn--icon-only m-btn--pill" title="Kazan Bilgilerini Düzenle">' +
'<i class="la la-edit"></i>' +
'</a>' +
'<a onclick="deleteBoiler(' + t.kazan_id + ')" class="m-portlet__nav-link btn m-btn m-btn--hover-danger m-btn--icon m-btn--icon-only m-btn--pill" title="Kazanı Sil">' +
'<i class="la la-trash"></i>' +
'</a>';
},
width: 250
}
]
});
I want to disable the row and checkbox if Total Value is Les then 500K or LTV ratio is less 45%. Additionally prevent selection of disabled rows to support select all checkbox in the header of the multiselect column
FIDDLE
$("#output").jqGrid({
url: "/echo/json/",
mtype: "POST",
datatype: "json",
postData: {
json: JSON.stringify(jsonData)
},
colModel: [
/** { name: 'ClientID', label:'ClientID',width: 80, key: true },****/
{
name: 'Symbol',
width: 65,
formatter: "showlink",
formatoptions: {
baseLinkUrl: "http://www.cnn.com",
idName: "",
addParam: function(options) {
return {
bankid: options.rowData.Symbol,
timePeriod: options.rowData.ShareQuantity
};
}
}
}, {
name: 'Description',
width: 165
}, {
name: 'ShareQuantity',
align: 'right',
width: 85,
classes: "hidden-xs",
labelClasses: "hidden-xs",
formatter: 'currency',
formatoptions: {
prefix: " ",
suffix: " "
}
}, {
name: 'SharePrice',
label: 'Share Price',
align: 'right',
width: 100,
classes: "hidden-xs",
labelClasses: "hidden-xs",
template: "number",
formatoptions: {
prefix: " $",
decimalPlaces: 4
}
},
/*{ label: 'Value1',
name: 'Value1',
width: 80,
sorttype: 'number',
formatter: 'number',
align: 'right'
}, */
{
name: 'TotalValue',
label: 'Total Value',
width: 160,
sorttype: 'number',
align: "right",
formatter: 'currency',
formatoptions: {
prefix: " $",
suffix: " "
}
}, {
name: 'LTVRatio',
label: 'LTV Ratio',
width: 70,
sorttype: 'number',
align: "right",
formatter: 'percentage',
formatoptions: {
prefix: " ",
suffix: " "
}
}, {
name: 'LTVCategory',
label: 'LTV Category',
classes: "hidden-xs",
labelClasses: "hidden-xs",
width: 120,
width: 165
},
{
name: 'MaxLoanAmt',
label: 'MaxLoanAmount',
width: 165,
sorttype: 'number',
align: "right",
formatter: 'currency',
formatoptions: {
prefix: " $",
suffix: " "
}
}
],
additionalProperties: ["Num1"],
/*beforeProcessing: function (data) {
var item, i, n = data.length;
for (i = 0; i < n; i++) {
item = data[i];
item.Quantity = parseFloat($.trim(item.Quantity).replace(",", ""));
item.LTVRatio = parseFloat($.trim(item.LTVRatio *10000).replace(",", ""));
item.Value = parseFloat($.trim(item.Value).replace(",", ""));
item.Num1 = parseInt($.trim(item.Num1).replace(",", ""), 10);
item.Num2 = parseInt($.trim(item.Num2).replace(",", ""), 10);
}
}, */
iconSet: "fontAwesome",
multiselect: true,
loadonce: true,
rownumbers: true,
cmTemplate: {
autoResizable: true,
editable: true
},
autoresizeOnLoad: true,
autoResizing: {
resetWidthOrg: true,
compact: true
},
autowidth: true,
height: 'auto',
forceClientSorting: true,
sortname: "Symbol",
footerrow: true,
caption: "<b>Collateral Value</b> <span class='pull-right' style='margin-right:20px;'>Valuation as of: " + mmddyyyy + "</span>",
loadComplete: function() {
var $self = $(this),
sum = $self.jqGrid("getCol", "Price", false, "sum"),
sum1 = $self.jqGrid("getCol", "MaxLoanAmt", false, "sum");
//ltvratio = $self.jqGrid("getCol","LTVRatio:addas", "Aved Loan Amount");
$self.jqGrid("footerData", "set", {
LTVCategory: "Max Approved Loan Amount:",
Price: sum,
MaxLoanAmt: sum1
});
}
});
You can use rowattr to disable the rows:
rowattr: function (item) {
var ratio = parseInt(item.LTVRatio, 10);
if (item.TotalValue < 500000 || ratio < 45) {
return {"class": "ui-state-disabled ui-jqgrid-disablePointerEvents"};
}
}
see the modified demo https://jsfiddle.net/OlegKi/615qovew/117/
I have kendo window popup from another grid where i want to show detail of selected record.i am not seeing data in the grid once i got response from server.I am new to Angularjs i need help to implement code in CTRL.JS Any help or suggetion will be appreciated.
code tried so far...
CTRL.JS
$scope.vendorWinOptions = subCategoryGridConfig.vendorWinConfig;
$scope.vendorDetailOptions = subCategoryGridConfig.VendorsDetailGrid;
$scope.showDetail = function(id) {
var dataToReturn = subCategoryGridConfig.VendorsDetailGrid;
dataToReturn.dataSource = {
transport : {
read : function(options) {
SubCategory.getAllVendors().then(function(response) {
options.success = (response.data);
})
}
}
}
return dataToReturn;
$scope.$broadcast('openDetailWindow');
};
FACTORY.JS
getAllVendors: function(subcategoryId){
return $http.get('/third-party-management/rest/vendor/' + subcategoryId);
}
JSON.JS
id: 1
parentAribaId: "18682"
subCatogeryCode: "X99.99.171"
subCatogeryName: "PROFESSIONAL SERVICES BUNDLED WITH TECHNOLOGY PURCHASES"
vendorAribaId: "18682"
vendorBusinessName: "SAP"
vendorLineOfBusiness: {id: 4, vendorBusinessIdentifier: "278070", primaryLOb: "GTO", secondaryLob1: "GHR",…}
id: 4
primaryLOb: "GTO"
secondaryLob1: "GHR"
secondaryLob2: "GHR"
vendorBusinessIdentifier: "278070"
vendorName: "SAP"
modalgridconfig.js
VendorsDetailGrid: {
scrollable: true,
filterable: false,
scrollable: false,
columns: [{
field: 'vdrDetail.parentAribaId',
title: 'Ariba ID',
width: '32px'
}, {
field: 'vdrDetail.vendorName',
title: 'Vendor Name',
width: '25px'
}, {
field: 'vdrDetail.vendorName',
title: 'Vendor Parent',
width: '30px'
}, {
field: 'vdrDetail.vendorBusinessName',
title: 'LOB Owner',
width: '30px'
}]
}
I figured it out how to make it work.
CTRL.JS
$scope.vendorWinOptions = subCategoryGridConfig.vendorWinConfig;
$scope.showDetail = function (vendor){
$scope.error = null;
$scope.selectedVendor = vendor;
SubCategory.getAllVendors().then(function(response){
$scope.selectedVendor.vendorValues = response.data;
$scope.vendorDetailWin.open().center();
$scope.$broadcast('openDetailWindow');
});
}
$scope.vendorDetailOptions = subCategoryGridConfig.VendorsDetailGrid;
subCategoryGridConfig.VendorsDetailGrid.dataSource = new kendo.data.DataSource({
data: [],
pageSize: 5
});
$scope.closeDetailModal = function(){
$scope.vendorDetailWin.close();
}
modalCtrl.js
angular.module('thirdPartyManagementApp').controller('vendorDetailModalCtrl', function($scope) {
'use strict';
$scope.$on('openDetailWindow', function () {
$scope.VendorsDetailGrid.setDataSource(new kendo.data.DataSource({
data: $scope.selectedVendor.vendorValues,
pageSize: 5
}));
});
});
FACTORY.JS
getAllVendors: function(){
return $http.get('/URL');
},
modalConfig.js
vendorWinConfig: {
width : '800px',
title : 'Vendors',
modal : true,
content : '/third-party-management/views/subCategories/vendorDetailModal.html',
visible : false,
},
VendorsDetailGrid: {
scrollable: true,
filterable: false,
scrollable: false,
columns: [{
field: 'vendorAribaId',
title: 'Ariba ID',
width: '20px'
}, {
field: 'vendorName',
title: 'Vendor Name',
width: '20px'
}, {
field: 'vendorBusinessName',
title: 'Vendor Parent',
width: '20px'
}, {
field: 'vendorLineOfBusiness.primaryLOb',
title: 'LOB Owner',
width: '20px'
}]
}
I had created a demo page using ExtJS for the first time.
I have created the .JS file as below.
Ext.require([
//'Ext.form.*',
//'Ext.layout.container.Column',
//'Ext.tab.Panel'
'*'
]);
Ext.onReady(function() {
Ext.QuickTips.init();
var bd = Ext.getBody();
var required = '<span style="color:red;font-weight:bold" data-qtip="Required">*</span>';
var simple = Ext.widget({
xtype: 'form',
layout: 'form',
collapsible: true,
id: 'userForm',
frame: true,
title: 'User Details',
bodyPadding: '5 5 0',
align: 'center',
width: 350,
buttonAlign: 'center',
fieldDefaults: {
msgTarget: 'side',
labelWidth: 75
},
defaultType: 'textfield',
items: [{
id: 'txtName',
fieldLabel: 'Name',
name: 'name',
afterLabelTextTpl: required,
allowBlank: false
}, {
id: 'dDOJ',
fieldLabel: 'Date Of Joining',
name: 'doj',
xtype: 'datefield',
format: 'd/m/Y',
afterLabelTextTpl: required,
allowBlank: false
}, {
id: 'txtAge',
fieldLabel: 'Age',
name: 'age',
xtype: 'numberfield',
minValue: 0,
maxValue: 100,
afterLabelTextTpl: required,
allowBlank: false
}, {
id: 'chkActive',
xtype: 'checkbox',
boxLabel: 'Active',
name: 'cb'
}],
buttons: [{
text: 'ADD',
listeners: {
click: {
fn: function() {
debugger;
if (Ext.getCmp('txtName').getValue() == "" || Ext.getCmp('dDOJ').getValue() == "" || Ext.getCmp('txtAge').getValue() == "") {
alert("Please Enter All Required Details!");
return false;
}
var reply = confirm("Are You Sure You Want To Save?")
if (reply != false) {
fnShowGrid();
}
}
}
}
}]
});
simple.render(document.body);
});
function fnShowGrid() {
debugger;
var vName = Ext.getCmp('txtName').getValue();
var vDOJ = Ext.Date.format(Ext.getCmp('dDOJ').getValue(), 'd/m/Y');
var vAge = Ext.getCmp('txtAge').getValue();
var vIsActive = "InActive";
if (Ext.getCmp('chkActive').getValue() == true) {
vIsActive = "Active";
}
var store = Ext.create('Ext.data.ArrayStore', {
storeId: 'myStore',
idIndex: 0,
fields: [
{ name: 'name' },
{ name: 'doj' },
{ name: 'age' },
{ name: 'active' }
],
//data: { name: vName, doj: vDOJ, age: vAge, active: vIsActive}
data: [[vName, vDOJ, vAge, vIsActive]]
});
store.load({
params: {
start: 1,
limit: 3
}
});
Ext.create('Ext.grid.Panel', {
title: 'User Details',
store: store,
columns: [
{
header: 'Name',
width: 160,
sortable: true,
dataIndex: 'name'
},
{
header: 'Date Of Join',
width: 75,
sortable: true,
dataIndex: 'doj'
},
{
header: 'Age',
width: 75,
sortable: true,
dataIndex: 'age'
},
{
header: 'Active',
width: 75,
sortable: true,
dataIndex: 'active'
}],
height: 200,
width: 400,
renderTo: Ext.getBody()
});
//detailsGrid.render(document.body);
}
The gridPanel is being displayed. But each time add a new data its creating a new grid!
I want to display GridPanel only once including all before added data.
Here's fiddle: http://jsfiddle.net/pratikhsoni/wc9mD/1/
Here is the working example based on your fiddle!
Ext.require([
'*'
]);
store = Ext.create('Ext.data.ArrayStore', {
storeId: 'myStore',
idIndex: 0,
fields: [
{ name: 'name' },
{ name: 'doj' },
{ name: 'age' },
{ name: 'active' }
],
//data: { name: vName, doj: vDOJ, age: vAge, active: vIsActive}
});
Ext.onReady(function() {
Ext.QuickTips.init();
var bd = Ext.getBody();
var required = '<span style="color:red;font-weight:bold" data-qtip="Required">*</span>';
var simple = Ext.widget({
xtype: 'form',
layout: 'form',
collapsible: true,
id: 'userForm',
frame: true,
title: 'User Details',
bodyPadding: '5 5 0',
align: 'center',
width: 350,
buttonAlign: 'center',
fieldDefaults: {
msgTarget: 'side',
labelWidth: 75
},
defaultType: 'textfield',
items: [{
id: 'txtName',
fieldLabel: 'Name',
name: 'name',
afterLabelTextTpl: required,
allowBlank: false
}, {
id: 'dDOJ',
fieldLabel: 'Date Of Joining',
name: 'doj',
xtype: 'datefield',
format: 'd/m/Y',
afterLabelTextTpl: required,
allowBlank: false
}, {
id: 'txtAge',
fieldLabel: 'Age',
name: 'age',
xtype: 'numberfield',
minValue: 0,
maxValue: 100,
afterLabelTextTpl: required,
allowBlank: false
}, {
id: 'chkActive',
xtype: 'checkbox',
boxLabel: 'Active',
name: 'cb'
}],
buttons: [{
text: 'ADD',
listeners: {
click: {
fn: function() {
debugger;
if (Ext.getCmp('txtName').getValue() == "" || Ext.getCmp('dDOJ').getValue() == "" || Ext.getCmp('txtAge').getValue() == "") {
alert("Please Enter All Required Details!");
return false;
}
var reply = confirm("Are You Sure You Want To Save?")
if (reply != false) {
fnShowGrid();
}
}
}
}
}]
});
simple.render(document.body);
});
function fnShowGrid() {
debugger;
var vName = Ext.getCmp('txtName').getValue();
var vDOJ = Ext.Date.format(Ext.getCmp('dDOJ').getValue(), 'd/m/Y');
var vAge = Ext.getCmp('txtAge').getValue();
var vIsActive = "InActive";
if (Ext.getCmp('chkActive').getValue() == true) {
vIsActive = "Active";
}
if (!Ext.getCmp('sample-grid')) {
store.add({
name: vName,
doj: vDOJ,
age: vAge,
active: vIsActive
});
Ext.create('Ext.grid.Panel', {
title: 'User Details',
store: store,
id: 'sample-grid',
columns: [
{
header: 'Name',
width: 160,
sortable: true,
dataIndex: 'name'
},
{
header: 'Date Of Join',
width: 75,
sortable: true,
dataIndex: 'doj'
},
{
header: 'Age',
width: 75,
sortable: true,
dataIndex: 'age'
},
{
header: 'Active',
width: 75,
sortable: true,
dataIndex: 'active'
}
],
height: 200,
width: 400,
renderTo: Ext.getBody()
});
} else {
store.add({
name: vName,
doj: vDOJ,
age: vAge,
active: vIsActive
});
}
}
First of All.
Its very good to see you getting touch with EXT js. Mistake's i will like to highlight in your code.
1. if (reply != false) {
fnShowGrid();
}
In this you are calling your grid to be created which is being called why you are creating a new grid . you just have to update the store.
Approach: You must call it only once check if it exist and if yes then update the store like this.
if (reply != false) {
if(!Ext.getCmp('hello')) {
fnShowGrid();
} else {
var store=Ext.getCmp('hello').getStore();
store.add ({
name: 'sadad',
doj:'25/01/2015',
age:'26',
active:'false'
});
store.reload();
}
}
So in all you have to update the store add the new records. I have hardcoded right now you can get the values as you have got when creating it.
Please find Updated fiddle.
Fiddle