ExtJS Cell Selection Model with PivotGrid Doesn't Work - javascript

I'm trying to change the SelectionModel of a PivotGrid and it isn't working. Here is my code. Can someone tell what I am doing wrong.
I need to use a cellSelectionModel as I want to drill down and I need the top and left axis to get the intersection points.
I have also tried the 'cellclick' event in the EXTJS 3.3 API with no luck. Anyone get a selection model other than the default RowSelectionModel working?
var pivotAccumGrid = new Ext.grid.PivotGrid({
store : my_store,
aggregator: 'count',
measure : 'my_field',
sm: new Ext.grid.CellSelectionModel({ //I have also tried selModel for key
listeners: {
cellselect: function(sm,row,col) {
Ext.Msg.alert('click','got a click!');
}
}
}),
topAxis: [ {dataIndex: 'top_field'},{dataIndex: 'top_field2'} ],
leftAxis: [ {dataIndex: 'left_field', width: 80} ],
});

This is a quick fix that introduces a new property to meta in PivotGridView so it can later be used to back out the cell indices. Most of the code isn't any different, just the introduction of meta.id in renderRows and the splitting of meta.id in getCellIndex.
Ext.override(Ext.grid.PivotGridView, {
renderRows : function(startRow, endRow) {
var grid = this.grid,
rows = grid.extractData(),
rowCount = rows.length,
templates = this.templates,
renderer = grid.renderer,
hasRenderer = typeof renderer == 'function',
getCellCls = this.getCellCls,
hasGetCellCls = typeof getCellCls == 'function',
cellTemplate = templates.cell,
rowTemplate = templates.row,
rowBuffer = [],
meta = {},
tstyle = 'width:' + this.getGridInnerWidth() + 'px;',
colBuffer, column, i;
startRow = startRow || 0;
endRow = Ext.isDefined(endRow) ? endRow : rowCount - 1;
for (i = 0; i < rowCount; i++) {
row = rows[i];
colCount = row.length;
colBuffer = [];
rowIndex = startRow + i;
//build up each column's HTML
for (j = 0; j < colCount; j++) {
cell = row[j];
meta.id = i + '-' + j;
meta.css = j === 0 ? 'x-grid3-cell-first ' : (j == (colCount - 1) ? 'x-grid3-cell-last ' : '');
meta.attr = meta.cellAttr = '';
meta.value = cell;
if (Ext.isEmpty(meta.value)) {
meta.value = ' ';
}
if (hasRenderer) {
meta.value = renderer(meta.value);
}
if (hasGetCellCls) {
meta.css += getCellCls(meta.value) + ' ';
}
colBuffer[colBuffer.length] = cellTemplate.apply(meta);
}
rowBuffer[rowBuffer.length] = rowTemplate.apply({
tstyle: tstyle,
cols : colCount,
cells : colBuffer.join(""),
alt : ''
});
}
return rowBuffer.join("");
},
getCellIndex : function(el) {
if (el) {
var match = el.className.match(this.colRe),
data;
if (match && (data = match[1])) {
return parseInt(data.split('-')[1], 10);
}
}
return false;
}
});

Related

Delete all empty cells in a column then shift all non empty cells up

Here is my code:
var ct = 0;
var sheet = SpreadsheetApp.getActiveSheet();
var cell = sheet.getCurrentCell();
var cellcol = cell.getColumn();
var cellrow = cell.getRow()
var notate = cell.getA1Notation();
var temp, letter = '';
var solved = new Array()
var pend = new Array()
var cellcol1 = cellcol + 1;
var p;
function copycell1() {
getFirstEmptyRowByColumnArray();
cell.copyTo(sheet.getRange(ct,cellcol,1,1))
cell.clearContent();
}
function getFirstEmptyRowByColumnArray() {
columnToLetter(cellcol)
var column = sheet.getRange(letter + ':' + letter);
var values = column.getValues();
while ( values[ct] && values[ct][0] !== "" ) {
ct++;
}
ct++
}
function getFirstEmptyRowByColumnArray2() {
columnToLetter(cellcol);
var cellrow = cell.getRow();
var column = sheet.getRange(letter + cellrow + ':' + letter);
var values = column.getValues();
while ( values[ct] && values[ct][0] !== "" ) {
ct++;
}
}
function columnToLetter(column)
{
while (column > 0)
{
temp = (column - 1) % 26;
letter = String.fromCharCode(temp + 65) + letter;
column = (column - temp - 1) / 26;
}
return letter;
}
function totalSolved() {
getFirstEmptyRowByColumnArray2()
var compacolumn = sheet.getRange(letter + cellrow + ':' + letter + (ct+cellrow));
var valuesSolved = compacolumn.getValues();
solved = valuesSolved
}
function totalPending() {
letter = '';
ct = 0;
cellcol = cellcol + 1;
getFirstEmptyRowByColumnArray2()
cellrow = cell.getRow();
var compacolumn = sheet.getRange(letter + cellrow + ':' + letter + (ct + cellrow));
var valuesPend = compacolumn.getValues();
pend = valuesPend
}
function compa() {
var i;
var o;
totalSolved();
totalPending();
for ( i = 0; i < pend.length; i++ ) {
for (o = 0; o < solved.length; o++) {
if (pend[i].toString() == solved[o].toString()) {
sheet.getRange(i+cellrow,cellcol1).clearContent();
}
else {
}
}
}
clearemp();
clearemp();
clearemp();
}
function clearemp() {
lastRowForColumn(cellcol1)
for (var i = 0; i < p; i++){
if((sheet.getRange(letter+(cellrow+i)).getValue()) == "")
{
Logger.log(sheet.getRange(letter+(cellrow+i)).getA1Notation());
sheet.getRange(letter+(cellrow+i)).deleteCells(SpreadsheetApp.Dimension.ROWS);
}
}
}
function lastRowForColumn(column){
var numRows = sheet.getLastRow();
Logger.log("numRows is " + numRows)
var data = sheet.getRange(1, column, numRows).getValues();
Logger.log("data is " + data)
Logger.log("data.length is " + data.length)
for(p = data.length - 1 ; p >= 0 ; p--){
if (data[p][0] != null && data[p][0] != ""){
Logger.log ("p is " + p)
return p + 1;
}
}
}
function test() {
Logger.log("cellcol is " + cellcol1)
lastRowForColumn(cellcol1)
Logger.log("p is " + p)
}
The function I'm talking about is compa().
The specific function that deletes the cells is clearemp(). But whenever I do it it is still not complete and I am at a loss on what to do
CONTEXT: I am working on comparing two lists and then removing the equal cells on the 2nd column and then shifting the cells up.
function delcels(col=1) {
const ss=SpreadsheetApp.getActive();
const sh=ss.getSheetByName('Sheet1');
const rg=sh.getRange(1,col,sh.getLastRow());
const c1=rg.getValues().filter((e)=>!(e===""));//thanks to iansedano
rg.clearContent();
sh.getRange(1,col,c1.length,1).setValues(c1);
}
A possible solution
There are a few approaches, but here is one, that is essentially the same as Cooper's, except that it doesn't clear values that are 0. Only if the cell is empty, i.e. "" will it clear the cell.
/**
* Clears empty cells in column
*
* #param columnToClear - the column that should be cleared, defaults to 1
* #param sheetName - the name of the sheet, defaults to "Sheet1"
*/
function clearBlanks(columnToClear = 1, sheetName = "Sheet1") {
const file = SpreadsheetApp.getActive();
const sheet = file.getSheetByName(sheetName);
const range = sheet.getRange(1, columnToClear, sheet.getLastRow(), 1);
const output = range.getValues().filter(e => !(e[0] === ""));
range.clearContent();
const outputRange = sheet.getRange(1, columnToClear, output.length, 1)
outputRange.setValues(output)
}
This gets the whole range into memory as a 2D array.
Uses filter to take out any values that are strictly equal === to and empty string. So it will not clear 0 values.
Clears the whole column, and pastes in the filtered array.
Filter
This is called on an array
array.filter(function)
You need to pass in a function that will return either a True or False value. The filter will go through each element and if it gets False then it will remove that element. In the example above, its passed in as an arrow function. When its an arrow function, if its on one line, you don't need to include the return statement.
There are a few useful functions that are like this. For example, forEach and map that can be very useful for the types of operation you are doing.
Reference
filter

How do I select dates between two dates with Javascript?

I have found similar threads about this but I cant seem to make their solutions work for my specific issue. I currently have a calendar that will highlight the starting date of an Event. I need to change this to highlight the Start Date through the End Date.
Note: I did not write this code. It seems like whoever wrote this left a lot of junk in here. Please don't judge.
attachTocalendar : function(json, m, y) {
var arr = new Array();
if (json == undefined || !json.month || !json.year) {
return;
}
m = json.month;
y = json.year;
if (json.events == null) {
return;
}
if (json.total == 0) {
return;
}
var edvs = {};
var kds = new Array();
var offset = en4.ynevent.getDateOffset(m, y);
var tds = $$('.ynevent-cal-day');
var selected = new Array(), numberOfEvent = new Array();
for (var i = 0; i < json.total; ++i) {
var evt = json.events[i];
var s1 = evt.starttime.toTimestamp();
var s0 = s1;
var s2 = evt.endtime.toTimestamp();
var ds = new Date(s1);
var de = new Date(s2);
var id = ds.getDateCellId();
index = selected.indexOf(id);
if (index < 0)
{
numberOfEvent[selected.length] = 1;
selected.push(id);
}
else
{
numberOfEvent[index] = numberOfEvent[index] + 1;
}
}
for (var i = 0; i < selected.length; i++) {
var td = $(selected[i]);
if (td != null) {
if (!(td.hasClass("otherMonth"))){
td.set('title', numberOfEvent[i] + ' ' + en4.core.language.translate(numberOfEvent[i] > 1 ? 'events' : 'event'));
td.addClass('selected');
}
}
}
},
Instead of trying to select them all, I recommend you iterate over them instead. So something like this:
function highlightDates(startDate, endDate) {
var curDate = startDate;
var element;
$('.selected').removeClass('selected'); // reset selection
while (curDate <= endDate) {
element = getElementForDate(curDate)
element.addClass('selected');
curDate.setDate(curDate.getDate() + 1); // add one day
}
}
function getElementForDate(someDate) {
return $('#day-' + someDate.getYear() + "-" + someDate.getMonth() + "-" + someDate.getDay());
}

Getting error while Exporting html table to excel

Im getting the following error while exporting an html table to excel;
SCRIPT429: Automation server can't create object...
This function was working fine but when i restarted my pc and the the application it stopped working not sure whats going on.
function write_to_excel() {
str = "";
var myTable = document.getElementById('myTable');
var rows = myTable.getElementsByTagName('tr');
var rowCount = myTable.rows.length;
var colCount = myTable.getElementsByTagName("tr")[0]
.getElementsByTagName("th").length;
var ExcelApp = new ActiveXObject("Excel.Application"); //Debug shows error at this line
var ExcelWorkbook = ExcelApp.Workbooks.Add();
var ExcelSheet = ExcelWorkbook.ActiveSheet;
ExcelApp.Visible = true;
ExcelSheet.Range("A1", "Z1").Font.Bold = true;
ExcelSheet.Range("A1", "Z1").Font.ColorIndex = 23;
// Format table headers
for ( var i = 0; i < 1; i++) {
for ( var j = 0; j < colCount - 1; j++) {
str = myTable.getElementsByTagName("tr")[i]
.getElementsByTagName("th")[j].innerHTML;
ExcelSheet.Cells(i + 1, j + 1).Value = str;
}
ExcelSheet.Range("A1", "Z1").EntireColumn.AutoFit();
}
for ( var i = 1; i < rowCount; i++) {
for ( var k = 0; k < colCount - 1; k++) {
str = rows[i].getElementsByTagName('td')[k].innerHTML;
ExcelSheet.Cells(i + 1, k + 1).Value = myTable.rows[i].cells[k].innerText;
}
ExcelSheet.Range("A" + i, "Z" + i).WrapText = true;
ExcelSheet.Range("A" + 1, "Z" + i).EntireColumn.AutoFit();
}
return;
}
Automation server can't create object.
Means your ActiveX settings are too high so the code will not run.

JavaScript - Generate Kendo Ui Grid using xml Data

I've Been using XSLT to display my xml page. I make use of the following to get the data from the xml file:
< xsl:value-of
select="ClinicalDocument/component/structuredBody/component[3]/section/text/table/tbody"/
>
After this, I have the following javascript to clean up the data and do the conversion:
-----------Get Content for Grids----------
//Split Content into array
var purposeArray = document.getElementById('purposeOfVisit').innerHTML.split("\n");
var activeProblemArray = document.getElementById('activeProblems').innerHTML.split("\n");
//------------ Remove All Unwanted Values-----------\\*/
var newDataString ="";
for( var k = 0; k < purposeArray.length; k++ )
{
newDataString += purposeArray[k] + "__";
}
newDataString = newDataString.replace(/ /g,"");
newDataString = newDataString.replace(/__________/g,"__-__");
var newDataArray = newDataString.split("__");
//------------- Save Values in final Array -------------\\*/
var semiFinalArray = new Array();
for( var x=0; x < newDataArray.length; x++)
{
if(newDataArray[x].length != 0)
{
semiFinalArray.push(newDataArray[x]);
}
}
var finalArray = new Array();
var counter = 0;
//------------ Find Number of Columns in row ------------\\*/
var numberOfRows = document.getElementById('numberOfRows').innerHTML;
var numberOfColumns = document.getElementById('numberOfColumns').innerHTML;
var columnsPerRow = parseInt(numberOfColumns) / parseInt(numberOfRows);
//------------------------------Testing ------------------------------//
var dataNamePre = "dataValue";
var temporaryArray = new Array();
var dataName;
//----------- Generate Grid Values -----------//
for( var b=0 ; b < semiFinalArray.length ; b = b + columnsPerRow)
{
var problemComment = "";
counter = 0;
var obj;
for( var a=0 ; a < columnsPerRow ; a++)
{
dataName = dataNamePre + counter.toString() + "";
//-------Generate Grid Titles------//
temporaryArray.push("Title " + (counter+1));
var key = "key"+a;
obj = { values : semiFinalArray[b+a] };
var problemComment = "";
finalArray.push(obj);
counter++;
}
}
//---------------------Generate GridArray---------------------------//
var gridArray = [];
var gridArrayHead = new Array();
counter = 0;
var objectValue = new Array();
for( var x = 0; x < finalArray.length; x++ )
{
objectValue = { head:temporaryArray[x], values: finalArray[x].values }
gridArray.push(objectValue);
}
var provFacilities = [];
for( var x = 0; x < finalArray.length; x++ )
{
provFacilities[x] =
{
head:temporaryArray[x], values: finalArray[x].values
}
}
//alert(gridArray);
$("#grid").kendoGrid(
{
columns:
[{
title:gridArray.head,
template:'#= values #'
}],
dataSource: {
data:finalArray,
pageSize:10
},
scrollable:false,
pageable:true
});
This may be a roundabout method, but I'm still prettry new to this method of coding.
Currently, all the data is being presented in one column, with the last value in my temporaryArray as the title for the column.
Everything works until I try to set the DataSource for the Kendo Grid. When working in the columns property in the grid, I made the following change:
title:gridArray[0].head
When this is done, the title is changed to the first value in the array.
What I want to know is how can I generate columns in the Kendo Grid According to the title? Is there a way to loop through all the values and create the objects from there, seeing that the date that is being sent to the grid are objects in an Array?
What I basically want is something to make this work, without the repitition:
var myGrid = $("#grid").kendoGrid( { columns: [ {
title: temporaryArray[0],
field: finalArray[0].values }, {
title: temporaryArray[1],
field: finalArray[1].values }, {
title: temporaryArray[2],
field: finalArray[2].values }, {
title: temporaryArray[3],
field: finalArray[3].values }, {
title: temporaryArray[4],
field: finalArray[4].values } ]
)};
Any help appreciated, thanks!
This issue has been fixed using the following coding:
var arrayData = [];
for( var x = 0; x < semiFinalArray.length; x=x+5 )
{
var tempArr = new Array();
for( var y = 0; y < 5; y++ )
{
var num = x + y;
tempArr.push(semiFinalArray[num]);
}
arrayData.push(tempArr);
}
var dataTitles = [];
for( var x = 0; x < titleArray.length; x++ )
{
var head = "";
head = titleArray[x];
head = head.replace(/ /g,"");
dataTitles.push(head);
}
var counter = 0;
var columnDefs = [];
for (var i = 0; i < columnsPerRow.length; i++)
{
if (counter == (columnsPerRow - 1))
{
counter = 0;
}
columnDefs.push({ field: dataTitles[counter], template: arrayData[i].values });
counter++;
}
// Create final version of grid array
var gridArray = [];
for (var i = 0; i < arrayData.length; i++)
{
var data = {};
for (var j = 0; j < dataTitles.length; j++)
{
data[dataTitles[j]] = arrayData[i][j];
}
gridArray.push(data);
}
// Now, create the grid using columnDefs as argument
$("#grid").kendoGrid(
{
dataSource:
{
data: gridArray,
pageSize: 10
},
columns: columnDefs,
scrollable: false,
pageable: true
}).data("kendoGrid");
With this, the data is displayed in the DataGrid.

JQGrid MultiSelect getting the column data

Is there a way for the JQGrid to return an array of column Data for using multiSelect as opposed to just an array of rowIds ?
At the moment I can only return the last column data that was selected.
jQuery("#buttonSelected").click(function() {
var ids = jQuery("#relatedSearchGrid").getGridParam('selarrrow');
var count = ids.length;
for (var i = 0; i < count; i++) {
var columnData = $("#relatedSearchGrid").find("tbody")[0].rows[$("#relatedSearchGrid").getGridParam('selrow') - 1].cells[1].innerHTML;
alert("In the loop and " + columnData );
}
if (count == 0) return;
var posturl = '<%= ResolveUrl("~") %>Rel******/AddSelected****/' + ids;
if (confirm("Add these " + count + " Docs?")) {
$.post(posturl,
{ ids: columnData },
function() { jQuery("#relatedSearchGrid").trigger("reloadGrid") },
"json");
}
})
Use getRowData to get the data for each row:
var rowData = $("#relatedSearchGrid").getRowData(ids[i]);
var colData = rowData.Name_Of_Your_Column;
var userListjqGrid = $('#UserListGrid'),
selRowId = userListjqGrid.jqGrid('getGridParam', 'selrow'),
userId = userListjqGrid.jqGrid('getCell', selRowId, 'UserId'),
userName = userListjqGrid.jqGrid('getCell', selRowId, 'UserName'),
subIds = $(subgridTableId).getGridParam('selarrrow'),
accessRuleIds = [];
for (var i = 0; i < subIds.length; i++) {
accessRuleIds[i] = $(subgridTableId).getRowData(subIds[i]).AccessRuleId;
}

Categories