Customize Ui-grid header field and enable sorting - javascript

I have a UI-grid which display few details in First Column beacon column I need to display count of all beacons along with Beacon(count) in header-text. this count m getting in response from a service.
This is my JS file
define([
'angular',
'./module',
'moment',
'select2'
], function(angular, module, moment, select2) {
'use strict';
module.controller('eventViewerSelectPanelController', [
'$scope',
'$translate',
'messageBus',
'toasty',
'$filter',
'$rootScope',
'$q',
'facilityDetails',
'logger',
'$interval',
'filterStateService',
'deviceStateService',
'$timeout',
'sensoryEventService',
'scarletConsoleConfigService',
function($scope, $translate, messageBus, toasty, $filter, $rootScope, $q, facilityDetails, logger, $interval, filterStateService, deviceStateService, $timeout, sensoryEventService, scarletConsoleConfigService) {
var macRegex = /^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$/i;
$scope.numberOfRecords = -1;
filterStateService.resetFilter();
var timestampColSortFun = function(a, b, rowA, rowB, direction){
console.log(a, b, rowA, rowB, direction);
return 1
}
$scope.loadSensoryEvents = function() {
var query = filterStateService.getSearchQuery().trim();
var deviceType = filterStateService.getActiveFilterState().toUpperCase();
var macListQuery = query.split(',');
var macList = [];
var errorMsg = '';
for(var item of macListQuery){
if(item != ''){
if(item.search(macRegex) > -1){
macList.push(item);
} else {
errorMsg = 'MAC not in valid format';
break;
}
}
}
if(errorMsg === '' && macList.length < 1){
errorMsg = 'Field is required.';
}
if(errorMsg === '' && macList.length > scarletConsoleConfigService.getConfig().eventMacMaxCount){
errorMsg = 'MAC entered exceeds the max allowed count.'
}
if(errorMsg != ''){
messageBus.send(Message.FilterPanelValidationFailed, errorMsg);
return;
}
$scope.processing = true;
console.log('duration', $scope.duration);
var eventPromise = sensoryEventService.load(query, deviceType,$scope.duration);
eventPromise.then(function(response) {
console.log(response)
var dataLength = response.sensoryEvents.length;
$scope.numberOfRecords = dataLength;
if(dataLength > 0){
$scope.gridOptions.data = processTimestamp(response.sensoryEvents);
**// Here m getting the count in response**
$scope.count = response.beaconCount;
console.log("value of count is=====",$scope.count);
$scope.receiverCount = response.receiverCount;
messageBus.send(Message.NumberOfSearchRecordsChanged, dataLength);
}
$scope.processing = false;
}, function(error) {
$scope.processing = false;
console.error('error getting events');
toasty.serviceError(error);
});
}
$scope.gridOptions = {
rowHeight: 60,
multiSelect: false,
enableColumnMenus: false,
enableEdit: false,
enableSoring: true,
enableHorizontalScrollbar: 0,
columnDefs: [{
name: 'beacon',
****// Here M adding count to display Name****
displayName:'Beacon(' +$scope.count + ')',
width: '25%',
cellTemplate: 'beacon-template'
},
{
name: 'receiver',
width: '25%',
headerCellTemplate: 'receiver-header-template',
cellTemplate: 'receiver-template'
},
{
name: 'storageTimestamp',
width: '30%',
displayName: 'Timestamps',
cellTemplate: 'timestamp-template'
// sortingAlgorithm: timestampColSortFun
},
{
name: 'rssi',
width: '7%',
displayName: 'RSSI',
cellTemplate: 'rssi-template'
},
{
name: 'beaconMajor',
width: '13%',
displayName:'Major/Minor',
cellTemplate:'major-minor-template'
}
]
};
$scope.select2DurationSettings = {
placeholder: 'Select',
width: '125px',
border: 'none',
minimumResultsForSearch: 10
};
// Initialize select2 functionality after page loads
$timeout(function() {
$('#selectDuration').select2($scope.select2DurationSettings);
}, 0);
$scope.durations = [
{
key: 'label.duration.5',
valueFrom: 0,
valueTo: 5
},
{
key: 'label.duration.15',
valueFrom: 0,
valueTo: 15
},
{
key: 'label.duration.30',
valueFrom: 0,
valueTo: 30
},
{
key: 'label.duration.60',
valueFrom: 0,
valueTo: 60
},
{
key: 'lable.duration.last.1-2',
valueFrom: 60,
valueTo: 120
},
{
key: 'lable.duration.last.2-3',
valueFrom: 120,
valueTo: 180
},
{
key: 'lable.duration.last.3-4',
valueFrom: 180,
valueTo: 240
}
];
$scope.duration = JSON.stringify($scope.durations[0]);
function processTimestamp(items) {
items.forEach(function(item, index) {
item.timestampUI = moment(item.storageTimestamp).format('L');
item.deviceTimestampUI = moment(item.deviceTimestamp).format('HH:mm:ss:SSS');
item.gatewayTimestampUI = moment(item.gatewayTimestamp).format('HH:mm:ss:SSS');
item.storageTimestampUI = moment(item.storageTimestamp).format('HH:mm:ss:SSS');
});
return items;
}
$scope.$onMessage(Message.SubmitFilterForm, function(event) {
$scope.loadSensoryEvents();
});
$(window).resize(function() {
$scope.getTableHeight();
});
$scope.getTableHeight = function() {
var height = $(window).height() - 160;
return {
height: (height) + "px"
};
};
}
]);
});
I have attached both screenshots actual and expected second one is expected one count is coming as undefined. Hoe can i get the count. Please reply Thanks.
The issue is grid is loading before the data is coming from response. How to resolve it?

Related

AngularJS, php & mysql database updation from datatable

I have the code with showing data from json file, but i need update table single row data to the database. In my code I can update only angulajs table. So i need one more thing, need to update that one mysql also. hence, i need to know how data will pass mysql to using js& PHP, the code is given below.
Script.js
var app = angular.module('app',
[
'ui.grid',
'ui.grid.pagination',
'ui.grid.selection',
'ui.grid.cellNav',
'ui.grid.expandable',
'ui.grid.edit',
'ui.grid.rowEdit',
'ui.grid.saveState',
'ui.grid.resizeColumns',
'ui.grid.pinning',
'ui.grid.moveColumns',
'ui.grid.exporter',
'ui.grid.infiniteScroll',
'ui.grid.importer',
'ui.grid.grouping'
]);
app.filter('genderFilter', function () {
var genderHash = {
'M': 'male',
'F': 'female'
};
app.gridApi.core.on.rowsRendered(scope,() => {
if (!gridApi.grid.expandable.expandedAll && !initialized)
{
gridApi.expandable.expandAllRows();
initialized = true;
}
});
return function (input) {
var result;
var match;
if (!input) {
return '';
} else if (result = genderHash[input]) {
return result;
} else if ((match = input.match(/(.+)( \([$\d,.]+\))/)) && (result = genderHash[match[1]])) {
return result + match[2];
} else {
return input;
}
};
});
app.filter('maritalFilter', function () {
var genderHash = {
'M': 'Married',
'S': 'Single'
};
return function (input) {
var result;
var match;
if (!input) {
return '';
} else if (result = genderHash[input]) {
return result;
} else if ((match = input.match(/(.+)( \([$\d,.]+\))/)) && (result = genderHash[match[1]])) {
return result + match[2];
} else {
return input;
}
};
})
app.controller('gridCtrl', ['$scope', '$http', '$log', '$timeout', 'uiGridConstants', '$q', '$interval',
function ($scope, $http, $log, $timeout, uiGridConstants, $q, $interval) {
$scope.gridOptions = {
enableRowSelection: true,
enableSelectAll: true,
selectionRowHeaderWidth: 35,
rowHeight: 35,
showGridFooter: true
};
$scope.convertDate = function (str) {
var date = new Date(str),
mnth = ("0" + (date.getMonth() + 1)).slice(-2),
day = ("0" + date.getDate()).slice(-2);
return [date.getFullYear(), mnth, day].join("/");
};
var expandableScope = {};
$scope.gridOptions = {
enableFiltering:true,
expandableRowTemplate: '<div style="padding:5px;"><div ui-grid="row.entity.subGridOptions[0]" ui-grid-edit ui-grid-row-edit ui-grid-selection style="height:340px;display:inline-block;"></div></div>',
expandableRowHeight: 350,
columnDefs: [
{ name: 'Project', enableCellEdit: true, },
/* {
name: "",
field:"fake",
cellTemplate: '<div class="ui-grid-cell-contents" >' +
'<button value="Edit" ng-if="!row.inlineEdit.isEditModeOn" ng-click="row.inlineEdit.enterEditMode($event)">Delete</button>' +
'<button value="Edit" ng-if="!row.inlineEdit.isEditModeOn" ng-click="row.inlineEdit.enterEditMode($event)">Edit</button>' +
'<button value="Edit" ng-if="row.inlineEdit.isEditModeOn" ng-click="row.inlineEdit.saveEdit($event)">Update</button>' +
'<button value="Edit" ng-if="row.inlineEdit.isEditModeOn" ng-click="row.inlineEdit.cancelEdit($event)">Cancel</button>' +
'</div>',
enableCellEdit: false,
enableFiltering:false,
enableSorting: false,
showSortMenu : false,
enableColumnMenu: false,
}*/
/*{ name: 'managerid', enableCellEdit: true },
//{
// name: 'hiredate', enableCellEdit: true, type: "date", cellFilter: 'date:"yyyy/MM/dd"',
// cellTemplate: '<div class="ui-grid-cell-contents">{{grid.appScope.convertDate(row.entity[col.field])}}</div>'
//},
{
name: 'title', enableCellEdit: true,
cellTemplate: '<div class="ui-grid-cell-contents"><div ng-class="{\'viewr-dirty\' : row.inlineEdit.entity[col.field].isValueChanged }">{{row.entity[col.field]}}</div></div>'
},
// { name: 'birthdate', enableCellEdit: true, type: "date", cellFilter: 'date:"yyyy/MM/dd"' },
{
name: 'maritalstatus', enableCellEdit: true, cellFilter: "maritalFilter",
editableCellTemplate: 'ui-grid/dropdownEditor',
editDropdownValueLabel: 'maritalstatus',
editDropdownOptionsArray: [
{ id: 'M', maritalstatus: 'Married' },
{ id: 'S', maritalstatus: 'Single' }]
},
{
name: 'gender', enableCellEdit: true, cellFilter: 'genderFilter',
editableCellTemplate: 'ui-grid/dropdownEditor',
editDropdownValueLabel: 'gender',
editDropdownOptionsArray: [
{ id: 'M', gender: 'male' },
{ id: 'F', gender: 'female' }]
},*/
],
enableGridMenu: true,
virtualizationThreshold: 60,
expandableRowScope: {
subGridVariable: 'subGridScopeVariable'
}
}
//$scope.gridOptions.multiSelect = true;
$http.get('https://rawgit.com/msrikanth508/uiGridInlineEditPOC/master/data/employeeData.json')
.success(function (data) {
$scope.gridOptions.data = data.slice(0, 55);; //[data[0], data[1]];
});
$scope.info = {};
$scope.gridOptions.onRegisterApi = function (gridApi) {
//set gridApi on scope
$scope.gridApi = gridApi;
gridApi.selection.on.rowSelectionChanged($scope, function (row) {
var msg = 'row selected ' + row.isSelected;
$log.log(msg);
});
gridApi.selection.on.rowSelectionChangedBatch($scope, function (rows) {
var msg = 'rows changed ' + rows.length;
$log.log(msg);
});
gridApi.edit.on.afterCellEdit($scope, function (rowEntity, colDef, newValue, oldValue) {
var selectedRows = $scope.gridApi.selection.getSelectedRows();
if (newValue != oldValue) {
rowEntity.state = "Changed";
//Get column
var rowCol = $scope.gridApi.cellNav.getFocusedCell().col.colDef.name;
angular.forEach(selectedRows, function (item) {
item[rowCol] = rowEntity[rowCol];// $scope.convertDate(rowEntity[rowCol]);
item.state = "Changed";
item.isDirty = false;
item.isError = false;
});
}
});
gridApi.rowEdit.on.saveRow($scope, function (rowEntity) {
// create a fake promise - normally you'd use the promise returned by $http or $resource
//Get all selected rows
var selectedRows = $scope.gridApi.selection.getSelectedRows();
//var rowCol = $scope.gridApi.cellNav.getFocusedCell().col.colDef.name;
var promise = $q.defer();
$scope.gridApi.rowEdit.setSavePromise(rowEntity, promise.promise);
$interval(function () {
if (rowEntity.gender === 'male') {
promise.reject();
} else {
promise.resolve();
}
}, 3000, 1);
})
gridApi.expandable.on.rowExpandedStateChanged($scope, function (row) {
if (row.isExpanded) {
row.entity.subGridOptions =[{
virtualizationThreshold: 60,
enableFiltering:true,
// expandableRowTemplate: '<div style="padding:5px;"><div ui-grid="row.entity.subGridOptions[0]" ui-grid-edit ui-grid-row-edit ui-grid-selection style="height:340px;display:inline-block;"></div></div>',
//expandableRowHeight: 350,
columnDefs: [
{ name: 'firstname', enableCellEdit: true, width: 100},
{ name: 'Activity Description', width: 500 },
{ name: 'Start' },
{ name: 'Department' },
{ name: 'Remarks' },
{
name: "",
field:"fake",
cellTemplate: '<div class="ui-grid-cell-contents" >' +
'<button value="Edit" ng-if="!row.inlineEdit.isEditModeOn" ng-click="row.inlineEdit.enterEditMode($event)">Delete</button>' +
'<button value="Edit" ng-if="!row.inlineEdit.isEditModeOn" ng-click="row.inlineEdit.enterEditMode($event)">Edit</button>' +
'<button value="Edit" ng-if="row.inlineEdit.isEditModeOn" ng-click="row.inlineEdit.saveEdit($event)">Update</button>' +
'<button value="Edit" ng-if="row.inlineEdit.isEditModeOn" ng-click="row.inlineEdit.cancelEdit($event)">Cancel</button>' +
'</div>',
enableCellEdit: false,
enableFiltering:false,
enableSorting: false,
showSortMenu : false,
enableColumnMenu: false,
}
],
onRegisterApi: function (gridApi) {
$scope.text = gridApi;
gridApi.selection.on.rowSelectionChanged($scope, function (row) {
console.log(row);
});
gridApi.rowEdit.on.saveRow($scope, function (rowEntity) {
// create a fake promise - normally you'd use the promise returned by $http or $resource
//Get all selected rows
var selectedRows = $scope.text.selection.getSelectedRows();
//var rowCol = $scope.gridApi.cellNav.getFocusedCell().col.colDef.name;
var promise = $q.defer();
$scope.text.rowEdit.setSavePromise(rowEntity, promise.promise);
$interval(function () {
if (rowEntity.gender === 'male') {
promise.reject();
} else {
promise.resolve();
}
}, 3000, 1);
})
}
}],
$http.get('https://rawgit.com/msrikanth508/uiGridInlineEditPOC/master/data/employeeContact.json')
.success(function (data) {
row.entity.subGridOptions[0].data = data.slice(0, 45);
});
}
});
};
}]);
angular.module('ui.grid').factory('InlineEdit', ['$interval', '$rootScope', 'uiGridRowEditService',
function ($interval, $rootScope, uiGridRowEditService) {
function inlineEdit(entity, index, grid) {
this.grid = grid;
this.index = index;
this.entity = {};
this.isEditModeOn = false;
this.init(entity);
}
inlineEdit.prototype = {
init: function (rawEntity) {
var self = this;
for (var prop in rawEntity) {
self.entity[prop] = {
value: rawEntity[prop],
isValueChanged: false,
isSave: false,
isCancel: false,
isEdit: false
}
}
},
enterEditMode: function (event) {
event && event.stopPropagation();
var self = this;
self.isEditModeOn = true;
// cancel all rows which are in edit mode
self.grid.rows.forEach(function (row) {
if (row.inlineEdit && row.inlineEdit.isEditModeOn && row.uid !== self.grid.rows[self.index].uid) {
row.inlineEdit.cancelEdit();
}
});
// Reset all the values
for (var prop in self.entity) {
self.entity[prop].isSave = false;
self.entity[prop].isCancel = false;
self.entity[prop].isEdit = true;
}
},
saveEdit: function (event) {
event && event.stopPropagation();
var self = this;
self.isEditModeOn = false;
for (var prop in self.entity) {
self.entity[prop].isSave = true;
self.entity[prop].isEdit = false;
}
uiGridRowEditService.saveRow(self.grid, self.grid.rows[self.index])();
},
cancelEdit: function (event) {
event && event.stopPropagation();
var self = this;
self.isEditModeOn = false;
for (var prop in self.entity) {
self.entity[prop].isCancel = true;
self.entity[prop].isEdit = false;
}
}
}
return inlineEdit;
}]);
index.html
<html>
<head>
<link data-require="bootstrap-css#*" data-semver="3.3.6" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css" />
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="https://rawgit.com/msrikanth508/uiGridInlineEditPOC/master/Css/ui-grid.css" />
<script src="https://rawgit.com/msrikanth508/uiGridInlineEditPOC/master/Js/vendor/angular.js"></script>
<script src="https://rawgit.com/msrikanth508/uiGridInlineEditPOC/master/Js/vendor/ui-grid.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="app" class="">
<div class="" ng-controller="gridCtrl">
<div ui-grid="gridOptions" ui-grid-move-columns="" ui-grid-edit="" ui-grid-row-edit="" ui-grid-selection="" ui-grid-expandable="" class="grid" style="height:800px"></div>
</div>
</body>
</html>
Thanks Advance

javascript code not picking up code_description value for first record

I have something similar to the JSFiddle mentioned here. The JSFiddle works fine, however, I am seeing a strange behaviour in my code. The description of very first
cell is always empty even though I am seeing that in the returned data (in JSON format) from the webservice, the description is present for each record. Please
take a look at the code below and let me know if I am missing anything:
this.processEmployees = function (data_, textStatus_, jqXHR_) {
var collection = data_.employees;
// A helper function used for employee codes below.
var isUsedKey = function (arrayOfObject, key) {
for (var i = 0; i < arrayOfObject.length; i += 1) {
if (arrayOfObject[i].key == key) {
return true;
}
}
return false;
};
var employeeCodes = [];
for (var i = 0; i < collection.length; i++) {
if (i == 0) {
var newItem = {};
newItem.key = collection[i].code_value;
newItem.dates = [collection[i].code_assignment_date];
newItem.description = collection[i].code_description;
newItem.hiringCriterion = collection[i].hiring_criteria;
newItem.name = collection[i].name;
console.log("Would like to check code_description for first item:",collection[i].code_description);
//debugger;
employeeCodes.push(newItem);
} else {
var item = collection[i];
var itemName = item.code_value;
var itemDate = item.code_assignment_date;
var itemDescription = item.code_description;
var hiringCriterion = item.hiring_criteria;
var itemCodeName = item.name;
if (isUsedKey(employeeCodes, itemName)) {
for (var j = 0; j < employeeCodes.length; j++) {
if (employeeCodes[j].key == itemName) {
var index = employeeCodes[j].dates.length;
employeeCodes[j].dates[index] = itemDate;
}
}
} else {
var nextNewItem = {};
nextNewItem.key = itemName;
nextNewItem.dates = [itemDate];
nextNewItem.code_description = itemDescription;
nextNewItem.hiring_criteria = hiringCriterion;
nextNewItem.name = itemCodeName;
employeeCodes.push(nextNewItem);
}
}
}
var newSource = {
localdata: employeeCodes,
datafields: [{
name: 'code_value',
type: 'string',
map: 'key'
},
{
name: 'code_assignment_date',
type: 'date',
map: 'dates>0'
},
{
name: 'name',
type: 'string'
},
{
name: 'code_description',
type: 'string'
},
{
name: 'hiring_criteria',
type: 'string'
}
],
datatype: "array"
};
var newAdapter = new $_.jqx.dataAdapter(newSource);
var iconrenderer = function (row, columnfield, value, defaulthtml, columnproperties) {
var icon = '';
if (employeeCodes[row].dates.length > 1) {
icon = '<img src="images/icon-down.png" style="position: absolute; right: 5px;" />';
}
return '<span style="position: relative; width: 100%; margin: 4px; float: ' + columnproperties.cellsalign + ';">' + newAdapter.formatDate(value, 'd') + icon + '</span>';
};
$_(self.gridSelector).jqxGrid({
source: newAdapter,
editable: true,
width: '600',
pageable: true,
sortable: true,
autoheight: true,
theme: 'classic',
height: '170',
columnsResize: true,
columns: [
{
text: 'Employee Name',
datafield: 'name',
width: 85,
},
{
text: 'Code Value',
datafield: 'code_value',
width: 75,
editable: false
},
{
text: 'Latest Date(s)',
datafield: 'code_assignment_date',
cellsformat: 'd',
columntype: 'combobox',
width: 100
createeditor: function (row, column, editor) {
var info = $_(self.gridSelector).jqxGrid('getrowdata', row);
console.log("length of info: " + info);
var groupName = info.code_value;
console.log("Contents of groupName: " + groupName);
var dates = [];
for (var i = 0; i < employeeCodes.length; i++) {
if (employeeCodes[i].key == groupName) {
dates = employeeCodes[i].dates;
}
}
editor.jqxComboBox({ autoDropDownHeight: false, source: dates, promptText: "Previous Date(s):", scrollBarSize: 10 });
},
initeditor: function (row, column, editor) {
var info = $_(self.gridSelector).jqxGrid('getrowdata', row);
var groupName = info.code_value;
var dates = [];
for (var i = 0; i < employeeCodes.length; i++) {
if (employeeCodes[i].key == groupName) {
dates = employeeCodes[i].dates;
}
}
editor.jqxComboBox({
autoDropDownHeight: false,
source: dates,
promptText: "Dates:",
width: 100,
scrollBarSize: 10,
renderer: function (index_, label_, value_) {
return formatDateString(value_);
},
renderSelectedItem: function (index, item) {
var records = editor.jqxComboBox('getItems');
var currentRecord = records[index].label;
return formatDateString(currentRecord);;
}
});
},
cellvaluechanging: function (row, column, columntype, oldvalue, newvalue) {
// return the old value, if the new value is empty.
if (newvalue == "") return oldvalue;
}
},
{
text: 'Description',
datafield: 'code_description'
},
{
text: 'Hiring Criterion',
datafield: 'hiring_criteria',
editable: false,
hidden: true
}
],
});
}; // End of processEmployees
For Example, if my JSON is the following:
{
"employees": [{
"code_value": "B1",
"code_assignment_date": "2016-12-13 23:04:00.0",
"code_type": 7,
"code_description": "This employee has received his salary",
"name": "Peter",
"hiring_criteria": null
}, {
"code_value": "A1",
"code_assignment_date": "2016-05-20 05:00:00.0",
"code_type": 7,
"code_description": "Employee has 5 vacation days left",
"name": "Jack",
"hiring_criteria": null
}],
"webServiceStatus": {
"status": "SUCCESS",
"message": "2 results"
}
}
I am not seeing the very first code_description value which is This employee has received his salary in the above JSON response whereas the following
line mentioned in the above code clearly shows it in the console panel:
console.log("Would like to check code_description for first item:",collection[i].code_description);
newItem.description = collection[i].code_description;
---Replace newItem.description to newItem.code_description in First object condition
newItem.hiringCriterion = collection[i].hiring_criteria;
---Replace newItem.hiringCriterion to newItem.hiring_criteria in First object condition

How to catch applied column filter in angular ui-grid

I'm working with ui-grid and server-side filtering. For each column I send a request to API with param based on filter value. By default param is empty
var filterOptions = {
filterBy: '&$filter=',
filterParam: ""
};
// and api call looks like
?$orderby=id-&pageSize=250&pageNbr=1&$filter=
if I setup any filter I send next request
param: filterOptions.filterParam = 'eventTypeId==' + evtTypeId
request: ?$orderby=id-&pageSize=250&pageNbr=1&$filter=eventTypeId==2
So what I want is pretty simple idea, I want to check if filter is already applied and send a request like
?$orderby=id-&pageSize=250&pageNbr=1&$filter=eventTypeId==2,studyId==1
but unfortunately I cannot catch any applied filters. I appreciate if somebody could help with my issue.
My code below
columnDef
$scope.gridOptions.columnDefs = [
{
field: 'title',
cellClass: getCellClass,
useExternalFiltering: true
}, {
field: 'description',
cellClass: getCellClass,
enableFiltering: true,
useExternalFiltering: true
}, {
displayName: 'Type',
field: 'eventType.name',
filter: {
selectOptions: $scope.eventType,
type: uiGridConstants.filter.SELECT
},
cellClass: getCellClass,
useExternalFiltering: true
}, {
displayName: 'Study Name',
field: 'study.name',
filter: {
selectOptions: $scope.study,
type: uiGridConstants.filter.SELECT
},
cellClass: getCellClass,
useExternalFiltering: true
}, {
displayName: 'Priority',
field: 'priority.name',
filter: {
selectOptions: $scope.priority,
type: uiGridConstants.filter.SELECT
},
cellClass: getCellClass,
useExternalFiltering: true
}, {
displayName: 'Severity',
field: 'severity.name',
filter: {
selectOptions: $scope.severity,
type: uiGridConstants.filter.SELECT
},
cellClass: getCellClass,
useExternalFiltering: true
}, {
displayName: 'Status',
field: 'status.name',
filter: {
selectOptions: $scope.status,
type: uiGridConstants.filter.SELECT
},
cellClass: getCellClass,
useExternalFiltering: true
}, {
displayName: 'Created',
field: 'occuredDate',
width: '12%',
filterHeaderTemplate: '<div class="row ui-grid-filter-container">' +
'<div ng-repeat="colFilter in col.filters" class="col-md-6 col-sm-6 col-xs-6">' +
'<div custom-grid-date-filter-header></div></div></div>',
filters: [
{
name: 'From',
condition: uiGridConstants.filter.GREATER_THAN_OR_EQUAL
},
{
name: 'To',
condition: uiGridConstants.filter.LESS_THAN_OR_EQUAL
}
],
cellFilter: 'date:"dd MMMM yyyy, h:mm:ss a"',
cellClass: getCellClass,
useExternalFiltering: false
}, {
displayName: 'Modified', field: 'createdDate',
width: '12%',
filterHeaderTemplate: '<div class="row ui-grid-filter-container">' +
'<div ng-repeat="colFilter in col.filters" class="col-md-6 col-sm-6 col-xs-6">' +
'<div custom-grid-date-filter-header></div></div></div>',
filters: [
{
name: 'From',
condition: uiGridConstants.filter.GREATER_THAN_OR_EQUAL
},
{
name: 'To',
condition: uiGridConstants.filter.LESS_THAN_OR_EQUAL
}
],
cellFilter: 'date:"dd MMMM yyyy, h:mm:ss a"',
cellClass: getCellClass,
useExternalFiltering: false
}
];
RegisterApi
$scope.gridOptions.onRegisterApi = function (gridApi) {
$scope.gridApi = gridApi;
gridApi.selection.selectRow($scope.gridOptions.data[0]);
gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
paginationOptions.pageNbr = '&pageNbr=' + newPage ;
paginationOptions.pageSize = '&pageSize=' + pageSize;
getData();
});
gridApi.core.on.filterChanged( $scope, function() {
var grid = this.grid;
// Define behavior for cancel filtering
$scope.isfilterclear = true;
angular.forEach(grid.columns, function( col ) {
if(col.filters[0].term){
$scope.isfilterclear = false;
}
});
if($scope.isfilterclear) {
$timeout(function() {
$rootScope.refresh()
},500);
}
// Filter behavior
$scope.textFilter = grid.columns[1].filters[0].term;
if($scope.textFilter) {
$scope.$watch('textFilter', function (newVal, oldVal) {
filterOptions.filterParam = 'title==*' + newVal + "*";
}, true);
getData()
}
$scope.desFilter = grid.columns[2].filters[0].term;
if($scope.desFilter) {
$scope.$watch('desFilter', function (newVal, oldVal) {
filterOptions.filterParam = 'description==*' + newVal + "*";
}, true);
getData()
}
for (var et = 0; et < $scope.eventType.length; et ++){
var evtType = $scope.eventType[et].name;
var evtTypeId = $scope.eventType[et].id;
filterOptions.filterParam = 'eventTypeId==' + evtTypeId;
if( grid.columns[3].filters[0].term === evtType ) {
getData()
}
}
for (var stud = 0; stud < $scope.study.length; stud ++){
var study = $scope.study[stud].name;
var studyId = $scope.study[stud].id;
filterOptions.filterParam = 'studyId==' + studyId;
if( grid.columns[4].filters[0].term === study ) {
getData()
}
}
for (var pr = 0; pr < $scope.priority.length; pr ++){
var priority = $scope.priority[pr].name;
var priorityId = $scope.priority[pr].id;
filterOptions.filterParam = 'priorityId==' + priorityId;
if( grid.columns[5].filters[0].term === priority ) {
getData()
}
}
for (var sev = 0; sev < $scope.severity.length; sev ++){
var severity = $scope.severity[sev].name;
var severityId = $scope.severity[sev].id;
filterOptions.filterParam = 'severityId==' + severityId;
if( grid.columns[6].filters[0].term === severity ) {
getData()
}
}
for (var stat = 0; stat < $scope.status.length; stat ++){
var status = $scope.status[stat].name;
var statusId = $scope.status[stat].id;
filterOptions.filterParam = 'statusId==' + statusId;
if( grid.columns[7].filters[0].term === status ) {
getData()
}
}
});
Where getData() is
var getData = function () {
eventService.getEventsWithParams(
sortOptions.orderBy,
sortOptions.directions,
paginationOptions.pageSize,
paginationOptions.pageNbr,
filterOptions.filterBy,
filterOptions.filterParam
)
.then(function (data) {
$scope.gridOptions.data = data;
// ***
angular.forEach($scope.gridOptions.data, function (val) {
val.occuredDate = new Date(val.occuredDate);
});
// $interval whilst we wait for the grid to digest the data we just gave it
$interval(function () {
$scope.gridApi.selection.selectRow($scope.gridOptions.data[0]);
}, 0, 1);
});
};
my plunker
(unfortunately I cannot provide the real API, but hope it will help anyhow)
The working code is
gridApi.core.on.filterChanged( $scope, function() {
// Declare vars
var grid = this.grid;
var columns = grid.columns;
$scope.columnTitle = grid.columns[1].filters[0].term;
$scope.columnDesc = grid.columns[2].filters[0].term;
var columnType = grid.columns[3].filters[0].term;
var columnStudy = grid.columns[4].filters[0].term;
var columnPriority = grid.columns[5].filters[0].term;
var columnSeverity = grid.columns[6].filters[0].term;
var columnStatus = grid.columns[7].filters[0].term;
var columnCreatedDate = grid.columns[8].filters[0].term;
var columnModifiedDate = grid.columns[9].filters[0].term;
// Create request for selectable filters
var query = [];
var string;
function request (id, param) {
if(param === "title==" || param === "description=="){
query.push(param + "*" + id + "*")
} else {
query.push(param + id);
}
if (query.length <= 1){
return query
} else {
string = query.join(";");
return string;
}
}
// Define behavior for cancel filtering
$scope.isfilterclear = true;
angular.forEach(columns, function( col ) {
if(col.filters[0].term){
$scope.isfilterclear = false;
}
});
if($scope.isfilterclear) {
$timeout(function() {
$rootScope.refresh()
},500);
}
// Filter behavior for columns
if($scope.columnTitle) {
$scope.$watch('columnTitle', function (newVal, oldVal) {
filterOptions.filterParam = request(newVal, 'title==*');
}, true);
getData()
}
if($scope.columnDesc) {
$scope.$watch('columnDesc', function (newVal, oldVal) {
filterOptions.filterParam = request(newVal, 'description==');
}, true);
getData()
}
if(columnType) {
filterOptions.filterParam = request(columnType, 'eventTypeId==');
getData();
}
if(columnStudy) {
filterOptions.filterParam = request(columnStudy, 'studyId==');
getData();
}
if(columnPriority) {
filterOptions.filterParam = request(columnPriority, 'priorityId==');
getData();
}
if(columnSeverity) {
filterOptions.filterParam = request(columnSeverity, 'severityId==');
getData();
}
if(columnStatus) {
filterOptions.filterParam = request(columnStatus, 'statusId==');
getData();
}
if(columnCreatedDate){
filterOptions.filterParam = request($rootScope.setFilterDate, 'occuredDate>=');
getData()
}
if(columnModifiedDate){
filterOptions.filterParam = request($rootScope.setFilterDate, 'occuredDate>=');
getData()
}
});
As you can see, I declared custom function with two params where I'm providing my request param for each call, I'm not sure about elegancy of this way but for two week I didn't find better solution

sencha navigation view overlapping on home listview

I am using sencha navigation view in my sencha application .
my bug scenario
I have list view with images on home screen first time it's load 20 record then scroll to down record will be increase by 20 on every scroll when i click on any image and redirect to another view like image detail view or profile view and come back to home on pressing back button all the images overlapped.
please help i am trying to solve this bug before 10 day's but not get success :- before overlapping
1) I am using navigation view it's extend with "Ext.dataview.DataView" and there is using
useComponents: true,
defaultType: 'productlistitem'
2) In 'productlistitem' extend with 'Ext.dataview.component.DataItem' In this view I am using update method witch set the image and other component data and also using dynamically method for image width , height .
below you can check my all views code
A) Home.js
Ext.define('demo.view.home.Home', {
extend: 'Ext.dataview.DataView',
requires: [
'demo.view.product.ListItem',
'demo.view.layout.ColumnLayout'
],
xtype: 'home',
config: {
scrollable: true,
plugins: {
xclass: 'demo.plugin.DataViewPaging', // Reference plugin by class
autoPaging: true
},
autoDestroy: true,
store: 'LookStore',
margin:'2 0',
useComponents: true,
defaultType: 'productlistitem',
cls: 'wow-home',
layout: {
type: 'column',
columnCount: 2,
columnWidth: 160
}
}
});
B) ListItem.js
var listItemData=[];
Ext.define('demo.view.product.ListItem', {
extend: 'Ext.dataview.component.DataItem',
requires: ['demo.view.product.Item'],
xtype: 'productlistitem',
config: {
padding: 2,
zIndex:999,
items: [{
xtype: 'item'
}]
},
initialize: function() {
console.log('initing the list item ');
var me = this;
me.callParent(arguments);
this.on('heightchange', 'recalculateHeight', me, {
delegate: '> item'
});
},
recalculateHeight: function() {
var me = this;
me.setHeight(me.innerElement.getHeight());
},
updateRecord: function(record) {
if (!record) {
return;
}
var me = this,
item = me.down('item');
me.callParent(arguments);
if (item) {
item.updateRecord(record, me.getDataview());
}
listItemData.push(item.id);
}
});
c) Item.js
Ext.define('demo.view.product.Item', {
extend: 'Ext.Container',
xtype: 'item',
requires: [
'Ext.Carousel',
'demo.view.product.ItemImage',
'demo.view.product.UserInfo',
'demo.view.product.InfoLabel'
],
config: {
record: null,
baseCls: 'wow-item',
showDescription: false,
items: [{
xtype: 'itemimage',
width: '100%'
}, {
xtype: 'userinfo',
height: 40,
listeners: {
painted: function() {
if (!this.element.hasListener('tap')) {
this.element.on('tap', function(e) {
e.stopPropagation();
var record = this.scope.up('item').getRecord();
if (!this.scope.getHandleListeners()) {
if(Ext.ComponentQuery.query('main')[0].getActiveItem().xtype === "wardrobedrawer")
demo.app.getController('ProductController').openProductDetail('', '', '', record);
return;
}
if (record && !Ext.isEmpty(record.raw.product_id) && !Ext.isEmpty(record.raw.importer)) {
var brandMerchantProducts = this.scope.up('brandmerchantproducts');
if (brandMerchantProducts) {
var currentTitle = demo.app.getController('HomeController').getMain().getActiveItem().config.title;
var currentItem = this.scope.element.dom.textContent;
if (currentTitle.toUpperCase() !== currentItem.toUpperCase()) {
demo.app.getController('ProductController').showMerchantProducts(record);
}
return;
}
demo.app.getController('ProductController').showMerchantProducts(record);
} else {
var list = this.scope.up('list');
demo.app.getController('ProfileController').goToOtherUserProfile(list, null, null, record.get('merchantId'), e);
}
}, {
scope: this
});
}
}
}
},
{
xtype: 'container',
height: 40,
margin:'1 0 0 0',
name: 'infoContainer',
layout:'hbox',
defaults: {
xtype: 'infolabel',
flex: 1
},
items: [{
iconCls: 'icon-diamond',
text: '09',
itemId: 'wows',
listeners: {
painted: function() {
if (!this.element.hasListener('tap')) {
this.element.on('tap', function(e) {
e.stopPropagation();
var record = this.scope.up('item').getRecord();
if (record.get('type') == 'product') {
demo.app.getController('ProductController').wowOrUnwowHomeProduct(record, this.scope.up('item'));
}
if (record.get('type') === 'look') {
demo.app.getController('ProductController').wowOrUnwowHomeLook(record, this.scope.up('item'));
}
}, {
scope: this
});
}
}
}
}, {
iconCls: 'icon-drawer',
text: '11',
itemId: 'lookOrAdd',
listeners: {
painted: function() {
if (!this.element.hasListener('tap')) {
this.element.on('tap', function(e) {
e.stopPropagation();
var record = this.scope.up('item').getRecord();
if (record.get('type') == 'product') {
demo.addedProductItem = this.scope.up('item');
demo.app.getController('ProductController').addProduct(record);
}
if (record.get('type') === 'look') {
demo.app.getController('ProductController').addHomeLook(record, this.scope.up('item'));
}
}, {
scope: this
});
}
}
}
}]
}
]
},
initialize: function() {
var me = this;
me.callParent(arguments);
me.on('load', 'imageLoaded', me, {
delegate: 'itemimage'
});
},
imageLoaded: function() {
var me = this;
me.setHeight(me.element.getHeight());
},
updateRecord: function(item, dataview) {
if (!item) {
return;
}
if (dataview && dataview.config.showDescription) {
this.setShowDescription(true);
}
var me = this;
me.setRecord(item);
if (item) {
var itemImage = this.down('itemimage'),
images = item.get('images'),
wows = item.get('wows') + '',
adds = item.get('adds') + '',
userInfo = this.down('userinfo');
if (images && images.length) {
itemImage.setSrc(images[0].original);
}
var type = item.get('type');
var lookOrProduct = me.down('#lookOrAdd');
var added = item.get('added');
var icon;
if (type === 'product') {
icon = 'icon-add-drawer';
lookOrProduct.setIconCls(icon);
} else {
icon = added ? 'icon-counterlook' : 'icon-addlookbook';
lookOrProduct.setIconCls(icon);
}
if (!Ext.isEmpty(item.raw.product_id)) {
userInfo.setAvatar('');
} else { // USER
var importer = item.get('importer');
if (importer) {
var avatar = importer.avatar;
if (avatar) {
userInfo.setAvatar(avatar);
} else {
userInfo.setAvatar('resources/images/default/default_avatar.jpg');
}
}
}
me.down('#wows').setText(wows);
if (!item.get('wowed')) {
me.down('#wows').addCls('grayedout-cls');
} else {
me.down('#wows').removeCls('grayedout-cls');
}
lookOrProduct.setText(adds);
if (!item.get('added')) {
lookOrProduct.addCls('grayedout-cls');
} else {
lookOrProduct.removeCls('grayedout-cls');
}
var infoContainer = this.down('container[name=infoContainer]');
if (infoContainer && infoContainer.isHidden()) {
infoContainer.show();
}
var title = Ext.ComponentQuery.query('main')[0].getActiveItem().title;
var storeId = this._record.stores[0].getStoreId();
if (type === 'product' && !Ext.isDefined(title) && storeId !== 'WowedStore' && storeId !== 'SearchStore' && storeId !== 'BrandMerchatProducts') {
var homeUrl = this._record.stores[0].getProxy().getUrl();
if ((homeUrl === demo.model.Config.apiServerPath('home')) || (homeUrl === demo.model.Config.apiServerPath('home'))) {
var noOfProducts = Ext.ComponentQuery.query('#productsInTheListId').length;
if (noOfProducts === 1) {
userInfo.setUsername(item);
if (me.getShowDescription()) {
infoContainer.hide();
userInfo.setAvatar('');
userInfo.setUsername(item);
userInfo.setHandleListeners(false);
}
} else {
userInfo.setUsername(item.get('author'));
if (me.getShowDescription()) {
infoContainer.hide();
userInfo.setAvatar('');
userInfo.setUsername(item.get('description'));
userInfo.setHandleListeners(false);
}
}
} else {
userInfo.setUsername(item);
if (me.getShowDescription()) {
infoContainer.hide();
userInfo.setAvatar('');
userInfo.setUsername(item);
userInfo.setHandleListeners(false);
}
}
} else {
userInfo.setUsername(item.get('author'));
if (me.getShowDescription()) {
infoContainer.hide();
userInfo.setAvatar('');
userInfo.setUsername(item.get('description'));
userInfo.setHandleListeners(false);
}
}
}
},
updateColorOfItem: function(item) {
var me = this,
lookOrProduct = me.down('#lookOrAdd');
if (!item.get('wowed')) {
me.down('#wows').addCls('grayedout-cls');
} else {
me.down('#wows').removeCls('grayedout-cls');
}
if (!item.get('added')) {
lookOrProduct.addCls('grayedout-cls');
} else {
lookOrProduct.removeCls('grayedout-cls');
}
}
});
D) ItemImage.js
Ext.define('demo.view.product.ItemImage', {
extend: 'Ext.Img',
xtype: 'itemimage',
config: {
},
onLoad: function(event) {
var me = this,
width = me.getParent().element.getWidth(), // me.element.getWidth() should work but I have found that sometimes it gives a width of 0. Now I go with a width of the parent.
imageObject = me.imageObject,
naturalWidth = imageObject.width,
naturalHeight = imageObject.height,
naturalRatio = naturalHeight / naturalWidth,
newHeight = naturalRatio * width;
me.setHeight(newHeight);
//Ext.ComponentQuery.query('productlistitem')[0].setHeight(newHeight+84);
me.callParent(event);
}
});
E) UserInfo.js
Ext.define('demo.view.product.UserInfo', {
extend: 'Ext.Container',
requires: ['Ext.Img'],
xtype: 'userinfo',
config: {
avatar: null,
username: null,
baseCls: 'wow-user-info',
handleListeners: true
},
applyAvatar: function(avatar) {
if (Ext.isEmpty(avatar)) {
return null;
}
return Ext.factory({
src: avatar,
cls: 'wow-avatar',
docked: 'left'
}, 'Ext.Img');
},
updateAvatar: function(newAvatar, oldAvatar) {
if (newAvatar) {
this.add(newAvatar);
}
if (oldAvatar) {
oldAvatar.destroy();
}
},
applyUsername: function(item) {
if (Ext.isObject(item)) {
var price_value = "",
price_currency = "",
itemName = "";
if (Ext.isDefined(item.raw.price)) {
if (Ext.isDefined(item.raw.price.value)) {
price_value = item.raw.price.value.toString();
}
}
if (Ext.isDefined(item.raw.price)) {
if (Ext.isDefined(item.raw.price.currency)) {
price_currency = item.raw.price.symbol;
}
}
if (item.raw.description === null) {
var item = item.data.author;
} else {
var item = item.raw.description;
}
item = item.toLowerCase();
itemName = item.charAt(0).toUpperCase() + item.slice(1);
if (Ext.isDefined(price_currency) && Ext.isDefined(price_value) && (price_currency !== "") && (price_value !== "")) {
itemName = '<div class="itemNames"><span style="font-size:0.9em" >' + price_currency.bold() + ' ' + price_value.bold() + '</span>' + " " + '<span style=" font-size:0.8em" class="itemName">' + itemName + '</span>' + '</div>';
} else {
itemName = '<div class="itemNames"><span style=" font-size:0.8em" class="itemName">' + itemName + '</span></div>';
}
return Ext.factory({
html: itemName,
xtype: 'component',
cls: 'wow-username-product'
});
} else {
return Ext.factory({
html: item,
xtype: 'component',
cls: 'wow-username'
});
}
},
updateUsername: function(newUsername, oldUsername) {
if (newUsername) {
this.add(newUsername);
}
if (oldUsername) {
oldUsername.destroy();
}
}
});
F) InfoLabel.js
Ext.define('demo.view.product.InfoLabel', {
extend: 'Ext.Button',
xtype: 'infolabel',
config: {
iconAlign: 'left',
cls: 'wow-info-label'
},
initialize: function() {
// Do nothing stopping unnecessary event listeners being added.
}
});

how to insert a button or some element into ext.js desktop/Panel?

i want to put some button into desktop, its not my code, from my friend which is abroad. i tried to put it in every place of this code but its not as a button there.
its lot of code for this Desktop View, please help me to understand where to put it.
Ext.define("TEST.view.desktop.Desktop", {
extend: "Ext.panel.Panel",
alias: "widget.TEST",
uses: [
"Ext.util.MixedCollection",
"Ext.menu.Menu",
"Ext.view.View", // dataview
"Ext.window.Window",
"TEST.view.desktop.TaskBar",
// "Ext.ux.desktop.Wallpaper"
"TEST.view.desktop.Toolbar"
],
requires: [
"TEST.view.desktop.DataprovidersDataView"
],
activeWindowCls: "ux-desktop-active-win",
inactiveWindowCls: "ux-desktop-inactive-win",
lastActiveWindow: null,
bodyCls: "ux-desktop",
border: false,
html: " ",
layout: "fit",
xTickSize: 1,
yTickSize: 1,
/**
* #cfg {Array|Store} shortcuts
* The items to add to the DataView. This can be a {#link Ext.data.Store Store} or a
* simple array. Items should minimally provide the fields in the
* {#link Ext.ux.desktop.ShorcutModel ShortcutModel}.
*/
shortcuts: null,
/**
* #cfg {String} shortcutItemSelector
* This property is passed to the DataView for the desktop to select shortcut items.
* If the {#link #shortcutTpl} is modified, this will probably need to be modified as
* well.
*/
shortcutItemSelector: "div.ux-desktop-shortcut",
/**
* #cfg {Object} toolbarConfig
* The config object for the toolbar.
*/
toolbarConfig: null,
/**
* #cfg {Object} taskbarConfig
* The config object for the TaskBar.
*/
taskbarConfig: null,
windowMenu: null,
initComponent: function() {
var me = this;
me.windowMenu = new Ext.menu.Menu(me.createWindowMenu());
me.bbar = me.taskbar = new TEST.view.desktop.TaskBar(me.taskbarConfig);
me.taskbar.windowMenu = me.windowMenu;
debugger;
me.tbar = me.toolbar = new TEST.view.desktop.Toolbar;
me.windows = new Ext.util.MixedCollection();
me.contextMenu = new Ext.menu.Menu(me.createDesktopMenu());
me.items = [
// { xtype: "wallpaper", id: me.id+"_wallpaper" },
{
xtype: "TESTdataprovidersdataview",
}];
me.callParent();
me.shortcutsView = me.items.getAt(0);
// var wallpaper = me.wallpaper;
// me.wallpaper = me.items.getAt(0);
// if (wallpaper) {
// me.setWallpaper(wallpaper, me.wallpaperStretch);
// }
},
afterRender: function() {
var me = this;
me.callParent();
me.el.on("contextmenu", me.onDesktopMenu, me);
},
//------------------------------------------------------
// Overrideable configuration creation methods
createDesktopMenu: function() {
var me = this, ret = {
items: me.contextMenuItems || []
};
if (ret.items.length) {
ret.items.push("-");
}
ret.items.push(
{ text: "Tile", handler: me.tileWindows, scope: me, minWindows: 1 },
{ text: "Show Toolbar", xtype: 'button', scope: me, minWindows: 1 },
{ text: "Cascade-test", handler: me.cascadeWindows, scope: me, minWindows: 1 });
return ret;
},
createWindowMenu: function() {
var me = this;
return {
defaultAlign: "br-tr",
items: [
{ text: "Restore", handler: me.onWindowMenuRestore, scope: me },
{ text: "Minimize", handler: me.onWindowMenuMinimize, scope: me },
{ text: "Maximize", handler: me.onWindowMenuMaximize, scope: me },
"-",
{ text: "Close", handler: me.onWindowMenuClose, scope: me }
],
listeners: {
beforeshow: me.onWindowMenuBeforeShow,
hide: me.onWindowMenuHide,
scope: me
}
};
},
// Event handler methods
onDesktopMenu: function(e) {
var me = this, menu = me.contextMenu;
e.stopEvent();
if (!menu.rendered) {
menu.on("beforeshow", me.onDesktopMenuBeforeShow, me);
}
menu.showAt(e.getXY());
menu.doConstrain();
},
onDesktopMenuBeforeShow: function(menu) {
var me = this, count = me.windows.getCount();
menu.items.each(function(item) {
var min = item.minWindows || 0;
item.setDisabled(count < min);
});
},
onWindowClose: function(win) {
var me = this;
me.windows.remove(win);
me.taskbar.removeTaskButton(win.taskButton);
me.updateActiveWindow();
},
//------------------------------------------------------
// Window context menu handlers
onWindowMenuBeforeShow: function(menu) {
var items = menu.items.items, win = menu.theWin;
items[0].setDisabled(win.maximized !== true && win.hidden !== true); // Restore
items[1].setDisabled(win.minimized === true); // Minimize
items[2].setDisabled(win.maximized === true || win.hidden === true); // Maximize
},
onWindowMenuClose: function() {
var me = this, win = me.windowMenu.theWin;
win.close();
},
onWindowMenuHide: function(menu) {
Ext.defer(function() {
menu.theWin = null;
}, 1);
},
onWindowMenuMaximize: function() {
var me = this, win = me.windowMenu.theWin;
win.maximize();
win.toFront();
},
onWindowMenuMinimize: function() {
var me = this, win = me.windowMenu.theWin;
win.minimize();
},
onWindowMenuRestore: function() {
var me = this, win = me.windowMenu.theWin;
me.restoreWindow(win);
},
//------------------------------------------------------
// Dynamic (re)configuration methods
getWallpaper: function() {
return this.wallpaper.wallpaper;
},
setTickSize: function(xTickSize, yTickSize) {
var me = this,
xt = me.xTickSize = xTickSize,
yt = me.yTickSize = (arguments.length > 1) ? yTickSize : xt;
me.windows.each(function(win) {
var dd = win.dd, resizer = win.resizer;
dd.xTickSize = xt;
dd.yTickSize = yt;
resizer.widthIncrement = xt;
resizer.heightIncrement = yt;
});
},
setWallpaper: function(wallpaper, stretch) {
this.wallpaper.setWallpaper(wallpaper, stretch);
return this;
},
//------------------------------------------------------
// Window management methods
cascadeWindows: function() {
var x = 0, y = 0,
zmgr = this.getDesktopZIndexManager();
zmgr.eachBottomUp(function(win) {
if (win.isWindow && win.isVisible() && !win.maximized) {
win.setPosition(x, y);
x += 20;
y += 20;
}
});
},
createWindow: function(win) {
var me = this;
win = me.add(win);
me.windows.add(win);
win.taskButton = me.taskbar.addTaskButton(win);
win.animateTarget = win.taskButton.el;
win.on({
activate: me.updateActiveWindow,
beforeshow: me.updateActiveWindow,
deactivate: me.updateActiveWindow,
minimize: me.minimizeWindow,
destroy: me.onWindowClose,
scope: me
});
win.on({
boxready: function() {
win.dd.xTickSize = me.xTickSize;
win.dd.yTickSize = me.yTickSize;
if (win.resizer) {
win.resizer.widthIncrement = me.xTickSize;
win.resizer.heightIncrement = me.yTickSize;
}
},
single: true
});
// replace normal window close w/fadeOut animation:
win.doClose = function() {
win.doClose = Ext.emptyFn; // dblclick can call again...
win.el.disableShadow();
win.el.fadeOut({
listeners: {
afteranimate: function() {
win.destroy();
}
}
});
};
return win;
},
getActiveWindow: function() {
var win = null,
zmgr = this.getDesktopZIndexManager();
if (zmgr) {
// We cannot rely on activate/deactive because that fires against non-Window
// components in the stack.
zmgr.eachTopDown(function(comp) {
if (comp.isWindow && !comp.hidden) {
win = comp;
return false;
}
return true;
});
}
return win;
},
getDesktopZIndexManager: function() {
var windows = this.windows;
// TODO - there has to be a better way to get this...
return (windows.getCount() && windows.getAt(0).zIndexManager) || null;
},
getWindow: function(id) {
return this.windows.get(id);
},
minimizeWindow: function(win) {
win.minimized = true;
win.hide();
},
restoreWindow: function(win) {
if (win.isVisible()) {
win.restore();
win.toFront();
} else {
win.show();
}
return win;
},
tileWindows: function() {
var me = this, availWidth = me.body.getWidth(true);
var x = me.xTickSize, y = me.yTickSize, nextY = y;
me.windows.each(function(win) {
if (win.isVisible() && !win.maximized) {
var w = win.el.getWidth();
// Wrap to next row if we are not at the line start and this Window will
// go off the end
if (x > me.xTickSize && x + w > availWidth) {
x = me.xTickSize;
y = nextY;
}
win.setPosition(x, y);
x += w + me.xTickSize;
nextY = Math.max(nextY, y + win.el.getHeight() + me.yTickSize);
}
});
},
updateActiveWindow: function() {
var me = this, activeWindow = me.getActiveWindow(), last = me.lastActiveWindow;
if (activeWindow === last) {
return;
}
if (last) {
if (last.el && last.el.dom) {
last.addCls(me.inactiveWindowCls);
last.removeCls(me.activeWindowCls);
}
last.active = false;
}
me.lastActiveWindow = activeWindow;
if (activeWindow) {
activeWindow.addCls(me.activeWindowCls);
activeWindow.removeCls(me.inactiveWindowCls);
activeWindow.minimized = false;
activeWindow.active = true;
}
me.taskbar.setActiveButton(activeWindow && activeWindow.taskButton);
}
});
if im inserting button here it will be so big as whole desktop. such a big buttons i dont need.
me.windows = new Ext.util.MixedCollection();
me.contextMenu = new Ext.menu.Menu(me.createDesktopMenu());
me.items = [
// { xtype: "wallpaper", id: me.id+"_wallpaper" },
{
xtype: "TESTdataprovidersdataview",
xtype: 'button',
text: 'Help'
}];
after comment of Cristoph tried this:
still not working, i see big button on whole dekstop
me.items = [
{
xtype: 'button',
width: 111,
height:111,
text: 'Show Toolbar',
action: 'showToolbar'
},
{
xtype: "TESTdataprovidersdataview"
}];
After many hours dealing with that, i realizied how simple it was.
Its all what i needed to implement:
me.items = [
{
xtype: 'button',
text: 'Show Toolbar',
maxWidth: 95,
maxHeight: 32,
margin: '5%, 800%',
itemId: 'niceButton',
align: "right",
action: 'showToolbar',
pack: 'center',
listeners: {
mouseout: function() {
if (!this.mouseout) {
this.mousedOver = true;
alert('Would you like to show Toolbar');
}
}
}
},
{
xtype: "TESTdataprovidersdataview"
}];

Categories