Possible to iterate through markers after applying a query in a FusionTablesLayer? - google-fusion-tables

I currently have a filter working on a fusion table rendered as a Map Layer, and I want to zoom to best fit all of the data whenever the filter is changed.
I figure I need to wait until the query is applied and then iterate through the markers to find the min/max x & y locations and pan to that rectangle, but I don't see a way in the Maps api to access the markers of a layer.
Anyone have an idea how to do this?

The short answer is no. To me this is one of the shortcomings of dealing with Fusion Tables via the Maps API. E.g. wanting to display a count of the results of my most recent query. But there is a work-around through the "undocumented" JSONP API to Fusion Tables. I've had great success using it but I must credit Robin Kraft with informing me about this API.
http://www.reddmetrics.com/2011/08/10/fusion-tables-javascript-query-maps.html.
Here's some code which allows you to re-execute your most recent query via an AJAX JSONP request and do what you want with the results, such as calculating the bounding-box. Note: this example uses Jquery for the AJAX JSONP calls. This example creates a <table> display but can be modified as needed.
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
// Example call
getFTData(tableid, 'latitude,longitude', example_dataHandler);
<script>
// Globals same for all requests
var queryUrlHead = 'https://fusiontables.googleusercontent.com/fusiontables/api/query?sql=';
var queryUrlTail = '&jsonCallback=?'; // ? could be a function name
// getFTData()
// table_id - Fusion Table id MUST have public permissions
// col_list - comma separated list of FT column names
// successFunction - function to parse the CSV results (see exampleParser below)
//////////////////////////////
function getFTData(table_id, col_list, successFunction) {
var query = "SELECT " + col_list + " FROM " + table_id;
var queryurl = encodeURI(queryUrlHead + query + queryUrlTail);
$.ajax({
type: "GET",
url: queryurl,
dataType: "jsonp", // return CSV FustionTable response as JSON
success: successFunction,
error: function () {alert("AJAX ERROR for " + queryurl ); }
});
}
function example_dataHandler(d) {
// get the actual data out of the JSON object
var cols = d.table.cols;
var rows = d.table.rows;
var row_count = 0;
var results = '<table border="1" cellpadding="4">';
results += '<tr>';
for (var i = 0; i < cols.length; i++) {
results += '<th>' + cols[i] + '</th>';
}
results += '</tr>';
// loop through all rows to add them to the map
for (var i = 0; i < rows.length; i++) {
// Per the expected columns
results += '<tr>';
for(j=0; j < rows[i].length; j++)
{
results += '<td>' + rows[i][j] + '</td>';
}
results += '</tr>';
row_count++;
}
results += '</table>';
results += '<br />';
results += 'Row Count: ' + row_count + '<br />';;
document.getElementById("program_select").innerHTML = results;
}
</script>
Since retrieving the count of recent Fusion Table rows returned is common, I'm adding a snippet of how to do that.
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
var tableid = 3167783
var where = "WHERE type = 9";
getFTCount(current_table_id, where, displayCount);
// Globals same for all request
var queryUrlHead = 'https://fusiontables.googleusercontent.com/fusiontables/api/query?sql=';
var queryUrlTail = '&jsonCallback=?'; // ? could be a function name
///////////////////////////////
// Get Counts from Fusion Tables.
// table_id required
// where optional "WHERE column == 'value' " where clause for count()
// successFunction callback required
///////////////////////////////
function getFTCount(table_id, where, successFunction) {
if(!table_id){
alert("table_id required.");
return;
}
if(!successFunction){
alert("successFunction callback required.");
return;
}
var query = "SELECT count() FROM " + table_id;
if(where){
query += ' ' + where;
}
var queryurl = encodeURI(queryUrlHead + query + queryUrlTail);
$.ajax({
type: "GET",
url: queryurl,
dataType: "jsonp", // return CSV FustionTable response as JSON
success: successFunction,
error: function () {alert("AJAX ERROR for " + queryurl ); }
});
}
function displayCount(d) {
var count = d.table.rows[0];
alert(count);
}
</script>

If your data is in a fusion table, then use the fusion table's sql api to find the Max/Min val for Lat and Lng respectively:
https://www.googleapis.com/fusiontables/v1/query?sql=SELECT
MINIMUM(Lat) AS MinLat, MAXIMUM(Lat) AS MaxLat,
MINIMUM(Long) AS MinLong, MAXIMUM(Long) AS MaxLong
FROM <table_id>
See here for full details on api: https://developers.google.com/fusiontables/docs/v1/sql-reference. (One thing to remember is to ecodeURI this sql statement)
This returns those for value to json array. And as I'm sure your aware, use these values to set your map's 'center' and 'zoom' parameters.

Related

Create jQuery ui dialog box for each row in a table

I am trying to append rows to a table using an array called searchResults. Everything works as expected until I introduce the jQuery UI dialog box. The problem is I need a new dialog box for each row in the first column. I'm pretty new to all of this so I'm pretty sure I'm using the index incorrectly at times. This is just to give you an idea of what I'm trying to accomplish. Any ideas how to do this correctly?
for (var i = 0; i < searchResults.length; i++)
{
$('#patientFileDialog[i]').dialog();
$'#openPFDialog[i]').click(function() {
$('#patientFileDialog[i]').dialog('open');
});
var dialog[i] = $(`<div id="patientFileDialog[i]" title="Patient File">${searchResults[i].patientWebLink}</div>`);
body.append('<tr>'+
`<td><button id="openPFDialog[i]">Click Here</button></td>` +
`<td>${searchResults[i].patientFirstName}</td>` +
`<td>${searchResults[i].patientLastName}</td>` +
`<td>${searchResults[i].patientDateOfBirth}</td>` +
`<td>${searchResults[i].patientDataPulseID}</td>` +
`<td>${searchResults[i].patientLaserFicheID}</td>` +
'</tr>')
}
After looking at your code a bit more I think I can see what you are trying to do. Working JSFiddle, with some faked searchResults so we can see it in action.
There are a few problems with the code in your question:
Using selectors like $('#patientFileDialog[i]') and $'#openPFDialog[i]') will try to match elements on the page with those IDs. AFAICT those don't actually exist yet, you are trying to create them.
var dialog[i] = ... sets up some divs as strings, but those are never added to the page;
As I mentioned in my comment, there are some syntax errors, maybe just typos and mixed up formatting here on SO;
Here's an updated version of the code. Notable changes:
Instead of adding an event handler for every individual openPFDialog button, it is better practice to add just one which matches them all. That single handler can then work out which button was clicked, and take the right action for just that one, not all of them. In this case if you have all your buttons use IDs that match openPFDialog-X, where X is a number, you can target anything matching that pattern (using a starts with selector, and find the X by removing the openPFDialog- part with replace.
There's an added complication with the above though. Selectors parsed at page load will only match elements that exist at that time. In this case, you're adding new elements to the page, and a selector defined at page load won't match them. The solution is to select instead some parent element which does exist at page load, and filter. This is called event delegation (search for the paragraph starting with "Delegated event handlers").
Working from what you have, I am guessing the patientFileDialogs you create should be placed inside some parent element which is not displayed on the page? That's what I've done.
Here's the code (and working JSFiddle):
var dialog, i;
// Single click handler for anything that starts with "openPFDialog-".
// Since those elements don't exist on the page yet, we need to instead
// select a parent object, say the body, and filter for clicks on our
// elements starting with our pattern
$('body').on('click', '[id^=openPFDialog]', function() {
// We need to find the "i"
i = $(this).attr('id').replace(/openPFDialog-/,'');
console.log('clicked on id', i);
$('#patientFileDialog-' + i).dialog();
});
for (var i = 0; i < searchResults.length; i++) {
// Create a new div with ID like "patientFileDialog-1", using the current
// search result
dialog = $('<div id="patientFileDialog-' + i + '" title="Patient File">' + searchResults[i].patientWebLink + '</div>');
// Add it to the page. I've use a div with ID dialogs which is hidden
$('#dialogs').append(dialog);
$('table').append('<tr>'+
'<td><button id="openPFDialog-' + i + '">Click Here</button></td>' +
'<td>' + searchResults[i].patientFirstName + '</td>' +
'<td>' + searchResults[i].patientLastName + '</td>' +
'<td>' + searchResults[i].patientDateOfBirth + '</td>' +
'<td>' + searchResults[i].patientDataPulseID + '</td>' +
'<td>' + searchResults[i].patientLaserFicheID + '</td>' +
'</tr>');
}
Update
One last suggestion - manipulating the DOM by adding/removing elements is slow. If you need to do that for each element in an array, it is best to avoid actually adding your content on each iteration, and rather just build up a string. Then once you're done iterating, just add the big single string, so you're chaning the DOM just once. Here's the basic changes needed to do that:
// Add some new variables to hold our big strings
var dialog, dialogs, row, rows, i;
// ... your code ...
for (var i = 0; i < searchResults.length; i++) {
// Create the dialog ...
dialog = ...
// Append it to our big string of all dialogs
dialogs += dialog;
// Same approach for rows
row = '<tr>'+ ... all that stuff
rows += row;
}
// Finished iterating, nothing added to DOM yet. Do it all at once::
$('#dialogs').append(dialogs);
$('table').append(rows);
Here is what I finally ended up having to do:
$(document).ready(function(){
if ($('[attr="searchResultsJson"]').length)
{
$('.approval-outer-wrap').prepend(drawTable());
$('.approval-outer-wrap').append('<div id="result-details" title="Search Result Detail"><p></p></div>')
}
$('body').on('click', '[id^=openPFDialog]', function() {
var result = $(this).parents('tr').data('result');
$('#result-details p').html(result.patientFirstName);
$('#result-details').dialog();
});
});
function drawTable(){
var table = $('<table id="search-results" />');
var header = $('<thead />');
table.append(header);
header.append('<tr><th>Patient File</th><th>First Name</th><th>Last Name</th><th>Date of Birth</th><th>Data Pulse ID</th><th>Laserfiche ID</th></tr>');
var body = $('<tbody />');
table.append(body);
var json = $('[attr="searchResultsJson"] [type="text"]').text();
var searchResults = JSON.parse(json);
for (var i = 0; i < searchResults.length; i++) {
body.append(`<tr data-result='${JSON.stringify(searchResults[i])}'>`+
`<td><button id="openPFDialog-` + i + `">🔍</button></td>` +
`<td>${searchResults[i].patientFirstName}</td>` +
`<td>${searchResults[i].patientLastName}</td>` +
`<td>${searchResults[i].patientDateOfBirth}</td>` +
`<td>${searchResults[i].patientDataPulseID}</td>` +
`<td>${searchResults[i].patientLaserFicheID}</td>` +
'</tr>');
}
return table;
}
Consider the following code.
function showPatientDialog(cnt){
$("#patient-file-dialog").html(cnt).dialog("open");
}
var d = $("<div>", {
id: "patient-file-dialog",
title: "Patient File"
})
.appendTo("body")
.dialog({
autoOpen: false
});
$.each(searchResults, function(i, result) {
var row = $("<tr>").appendTo(body);
$("<td>").appendTo(row).html($("<button>", {
id: "open-pdf-dialog-" + i
}).click(function() {
showPatientDialog(result.patientWebLink);
}));
$("<td>").appendTo(row).html(result.patientFirstName);
$("<td>").appendTo(row).html(result.patientLastName);
$("<td>").appendTo(row).html(result.patientDateOfBirth);
$("<td>").appendTo(row).html(result.patientDataPulseID);
$("<td>").appendTo(row).html(result.patientLaserFicheID);
});

Extract URL from copied text in Google Sheets [duplicate]

I have a sheet where hyperlink is set in cell, but not through formula. When clicked on the cell, in "fx" bar it only shows the value.
I searched on web but everywhere, the info is to extract hyperlink by using getFormula().
But in my case there is no formula set at all.
I can see hyperlink as you can see in image, but it's not there in "formula/fx" bar.
How to get hyperlink of that cell using Apps Script or any formula?
When a cell has only one URL, you can retrieve the URL from the cell using the following simple script.
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var url = sheet.getRange("A2").getRichTextValue().getLinkUrl(); //removed empty parentheses after getRange in line 2
Source: https://gist.github.com/tanaikech/d39b4b5ccc5a1d50f5b8b75febd807a6
When Excel file including the cells with the hyperlinks is converted to Google Spreadsheet, such situation can be also seen. In my case, I retrieve the URLs using Sheets API. A sample script is as follows. I think that there might be several solutions. So please think of this as one of them.
When you use this script, please enable Sheets API at Advanced Google Services and API console. You can see about how to enable Sheets API at here.
Sample script:
var spreadsheetId = "### spreadsheetId ###";
var res = Sheets.Spreadsheets.get(spreadsheetId, {ranges: "Sheet1!A1:A10", fields: "sheets/data/rowData/values/hyperlink"});
var sheets = res.sheets;
for (var i = 0; i < sheets.length; i++) {
var data = sheets[i].data;
for (var j = 0; j < data.length; j++) {
var rowData = data[j].rowData;
for (var k = 0; k < rowData.length; k++) {
var values = rowData[k].values;
for (var l = 0; l < values.length; l++) {
Logger.log(values[l].hyperlink) // You can see the URL here.
}
}
}
}
Note:
Please set spreadsheetId.
Sheet1!A1:A10 is a sample. Please set the range for your situation.
In this case, each element of rowData is corresponding to the index of row. Each element of values is corresponding to the index of column.
References:
Method: spreadsheets.get
If this was not what you want, please tell me. I would like to modify it.
Hey all,
I hope this helps you save some dev time, as it was a rather slippery one to pin down...
This custom function will take all hyperlinks in a Google Sheets cell, and return them as text formatted based on the second parameter as either [JSON|HTML|NAMES_ONLY|URLS_ONLY].
Parameters:
cellRef : You must provide an A1 style cell reference to a cell.
Hint: To do this within a cell without hard-coding
a string reference, you can use the CELL function.
eg: "=linksToTEXT(CELL("address",C3))"
style : Defines the formatting of the output string.
Valid arguments are : [JSON|HTML|NAMES_ONLY|URLS_ONLY].
Sample Script
/**
* Custom Google Sheet Function to convert rich-text
* links into Readable links.
* Author: Isaac Dart ; 2022-01-25
*
* Params
* cellRef : You must provide an A1 style cell reference to a cell.
* Hint: To do this within a cell without hard-coding
* a string reference, you can use the CELL function.
* eg: "=linksToTEXT(CELL("address",C3))"
*
* style : Defines the formatting of the output string.
* Valid arguments are : [JSON|HTML|NAMES_ONLY|URLS_ONLY].
*
*/
function convertCellLinks(cellRef = "H2", style = "JSON") {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.getActiveSheet();
var cell = sheet.getRange(cellRef).getCell(1,1);
var runs = cell.getRichTextValue().getRuns();
var ret = "";
var lf = String.fromCharCode(10);
runs.map(r => {
var _url = r.getLinkUrl();
var _text = r.getText();
if (_url !== null && _text !== null) {
_url = _url.trim(); _text = _text.trim();
if (_url.length > 0 && _text.length > 0) {
switch(style.toUpperCase()) {
case "HTML": ret += '' + _text + '}' + lf; break;
case "TEXT": ret += _text + ' : "' + _url + '"' + lf; break;
case "NAMES_ONLY" : ret += _text + lf; break;
case "URLS_ONLY" : ret += _url + lf; break;
//JSON default : ...
default: ret += (ret.length>0?(','+ lf): '') +'{name : "' + _text + '", url : "' + _url + '"}' ; break;
}
ret += lf;
}
}
});
if (style.toUpperCase() == "JSON") ret = '[' + ret + ']';
//Logger.log(ret);
return ret;
}
Cheers,
Isaac
I tried solution 2:
var urls = sheet.getRange('A1:A10').getRichTextValues().map( r => r[0].getLinkUrl() ) ;
I got some links, but most of them yielded null.
I made a shorter version of solution 1, which yielded all the links.
const id = SpreadsheetApp.getActive().getId() ;
let res = Sheets.Spreadsheets.get(id,
{ranges: "Sheet1!A1:A10", fields: "sheets/data/rowData/values/hyperlink"});
var urls = res.sheets[0].data[0].rowData.map(r => r.values[0].hyperlink) ;

Google spreadsheet: Download all the sheets at once

When working with google spreadsheet, how to download all the sheets at once?
I want to use the option:
Comma-separated values
But it only download the current sheet, how to get them all?
For anyone who navigates to this question, trying to download all the tabs in their Google spreadsheets as CSV files at once, even in 2021, there does not seem to be a GUI button to do this. At least I could not see anything. The answer by #Amit Agarwal does well, to get all sheets, but if your file has comma-delimited data in cells, then data could get mangled.
I took Amit's approach https://stackoverflow.com/a/28711961 and combined it with Michael Derazon and Aaron Davis's approach here https://gist.github.com/mrkrndvs/a2c8ff518b16e9188338cb809e06ccf1 to dump all the tabs of a chosen Google spreadsheet into a folder in Google Drive. You can then just download the folder with a single click.
The following is Google script, not exactly a Javascript, and you would have to copy-paste this in https://script.google.com/ login with your Google id, and then create a project and then create a script app, and save and execute this.
// https://stackoverflow.com/a/28711961
function export_sheets_as_csv_to_folder() {
// Sheet id is in URL https://docs.google.com/spreadsheets/d/YOUR_SHEET_ID/edit#gid=IGNORE
var ss = SpreadsheetApp.openById('YOUR_SHEET_ID');
var sheets = ss.getSheets();
if (sheets === undefined || sheets.length === 0) {
return;
}
var passThroughFolder = DriveApp.createFolder('YOUR_PREFERRED_FOLDER_NAME_IN_DRIVE');
for (var s in sheets) {
var csv = convertRangeToCsvFile_(sheets[s])
passThroughFolder.createFile(sheets[s].getName() + ".csv", csv);
}
}
// https://gist.github.com/mrkrndvs/a2c8ff518b16e9188338cb809e06ccf1
function convertRangeToCsvFile_(sheet) {
// get available data range in the spreadsheet
var activeRange = sheet.getDataRange();
try {
var data = activeRange.getValues();
var csvFile = undefined;
// loop through the data in the range and build a string with the csv data
if (data.length > 1) {
var csv = "";
for (var row = 0; row < data.length; row++) {
for (var col = 0; col < data[row].length; col++) {
if (data[row][col].toString().indexOf(",") != -1) {
data[row][col] = "\"" + data[row][col] + "\"";
}
}
// join each row's columns
// add a carriage return to end of each row, except for the last one
if (row < data.length-1) {
csv += data[row].join(",") + "\r\n";
}
else {
csv += data[row];
}
}
csvFile = csv;
}
return csvFile;
}
catch(err) {
Logger.log(err);
Browser.msgBox(err);
}
}
After clicking download > pdf, select export > worksheet (instead of current sheet which is the default)
You can use Google Scripts to save all the sheets of a spreadsheet into separate files.
function myFunction() {
var ss = SpreadsheetApp.openById(SHEET_ID);
var sheets = ss.getSheets();
for (var s in sheets) {
var csv = "";
var data = sheets[s].getDataRange().getValues();
for (d in data) {
csv += data[d].join(",") + "\n";
}
DriveApp.createFile(sheets[s].getName() + ".csv", csv);
}
}
the answer from #Soham works amazingly but it doesn't handle multiline values. It would be an easy fix just to add more checks to character \n along with , but I took the liberty to rewrite the function using map (and string.includes) so it is more concise.
function convertRangeToCsvFile_(sheet) {
return sheet.getDataRange().getValues()
.map(row => row.map(value => value.toString())
.map(value => (value.includes("\n") || value.includes(",")) ? "\"" + value + "\"" : value)
.join(','))
.join('\n')
}
A slight variation on this that uses a zip instead of a folder to contain the sheets and does some modernizing of the great work done by keychera and Soham's answer.
You can use this as a bound script and it will add a menu item to the extensions menu:
// Code.gs
function exportSheetsToDrive() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheets = ss.getSheets();
if (sheets === undefined || sheets.length === 0) {
return;
}
const now = new Date();
const csvBlobs = sheets.map((sheet) => {
const name = sheet.getName();
const csv = convertSheetToCsv(sheet);
Logger.log({ name, length: csv.length });
return Utilities.newBlob(csv, MimeType.CSV, `${name}.csv`)
});
const zipName = `export_${ss.getName()}_${now.toISOString()}.zip`;
const zip = Utilities.zip(csvBlobs, zipName);
DriveApp.createFile(zip);
}
function convertSheetToCsv(sheet) {
return sheet
.getDataRange()
.getValues()
.map((row) =>
row
.map((value) => value.toString())
.map((value) =>
value.includes("\n") || value.includes(",")
? '"' + value + '"'
: value
)
.join(",")
)
.join("\n");
}
and
// Menu.gs
function onOpen(e) {
const menu = SpreadsheetApp.getUi().createAddonMenu();
menu
.addItem('Export all sheets as CSV to Drive', 'exportSheetsToDrive')
.addToUi();
}
function onInstall(e) {
onOpen(e);
}

Open infowindow with sidebar on Google Fusion Table

For the life of me, I can't get this map to open infowindows on the sidebar link clicks: http://web.redding.com/static/redd/asphalt/prod/xmas-lights-2014-complex.html
Here's the fusion table: https://www.google.com/fusiontables/DataSource?docid=1WrvKdTypAmZozAIVeOw4vBX2g1hPInyVyuqn8GUM
Which looks like this (CSV):
Location,Description,Photo,Winner,Name
"1101 Twin View Boulevard, Redding CA",Redding's finest media organization with decades of experience & class.,http://mediaassets.redding.com/photo/2014/03/15/youthcamp17b-01_3471502_ver1.0.jpg,,The Record Searchlight
"1500 Court Street, Redding CA",Shasta Courthouse,,,
"777 Cypress Avenue, Redding CA",City Hall,,,
All I want to do is be able to click on the links in the sidebar and have the associated infowindow open on the map.
I'm new to javascript so I wouldn't be surprised if there's something obvious I'm overlooking.
Code from the linked page:
function createSidebar() {
//set the query using the parameter
var query = new google.visualization.Query(queryText);
var queryText = encodeURIComponent("SELECT 'Name','Description' FROM 1uQLxgNdNR_etBFP8O_0YNDA38PqyZB3NidIJfsgX");
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + queryText);
//set the callback function
query.send(getData);
}
function myFTclick(row) {
var Name = FTresponse.getDataTable().getValue(row,0);
var Description = FTresponse.getDataTable().getValue(row,1);
var Location = FTresponse.getDataTable().getValue(row,2);
var Photo = FTresponse.getDataTable().getValue(row,5);
var Winner = FTresponse.getDataTable().getValue(row,7);
var position = new google.maps.LatLng(lat, lng);
// Set up and create the infowindow
if (!infoWindow) infoWindow = new google.maps.InfoWindow({});
var content = '<div class="FT_infowindow">' + name;
if (Description) content += '<br>'+Description;
if (Location) content += '<br>'+Location;
if (Photo) content += '<br>'+Photo;
if (extraContent) content += "<br>["+extraContent+"]";
content += '<br>'+'zoom in';
content += '</div>';
infoWindow.setOptions({
content: content,
pixelOffset: null,
position: position
});
// Infowindow-opening event handler
infoWindow.open(map);
}
var FTresponse = null;
//define callback function, this is called when the results are returned
function getData(response) {
if (!response) {
alert('no response');
return;
}
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
FTresponse = response;
//for more information on the response object, see the documentation
//http://code.google.com/apis/visualization/documentation/reference.html#QueryResponse
numRows = response.getDataTable().getNumberOfRows();
numCols = response.getDataTable().getNumberOfColumns();
//concatenate the results into a string, you can build a table here
fusiontabledata = "<table><tr>";
fusiontabledata += "<th>" + response.getDataTable().getColumnLabel(1) + "</th>";
fusiontabledata += "</tr><tr>";
for(i = 0; i < numRows; i++) {
fusiontabledata += "<td><a href='javascript:myFTclick("+i+")'>"+response.getDataTable().getValue(i, 1) + "</a></td>";
fusiontabledata += "</tr><tr>";
}
fusiontabledata += "</table>"
//display the results on the page
document.getElementById('sidebar').innerHTML = fusiontabledata;
}
You have a javascript error in your code, look at the javascript console: Uncaught Error: Invalid column index 2. Should be an integer in the range [0-1].
Your query only includes two columns from the table:
var queryText = encodeURIComponent("SELECT 'Name','Description' FROM 1uQLxgNdNR_etBFP8O_0YNDA38PqyZB3NidIJfsgX");
Which means you can't get any columns beyond 0 and 1, so this will not work:
function myFTclick(row) {
var Name = FTresponse.getDataTable().getValue(row,0);
var Description = FTresponse.getDataTable().getValue(row,1);
var Location = FTresponse.getDataTable().getValue(row,2);
var Photo = FTresponse.getDataTable().getValue(row,5);
var Winner = FTresponse.getDataTable().getValue(row,7);
You need to include those in your query:
var queryText = encodeURIComponent("SELECT 'Name','Description','Location','Photo','Winner' FROM 1uQLxgNdNR_etBFP8O_0YNDA38PqyZB3NidIJfsgX");
Then access them in that order:
function myFTclick(row) {
var Name = FTresponse.getDataTable().getValue(row,0);
var Description = FTresponse.getDataTable().getValue(row,1);
var Location = FTresponse.getDataTable().getValue(row,2);
var Photo = FTresponse.getDataTable().getValue(row,3);
var Winner = FTresponse.getDataTable().getValue(row,4);

JQGrid Filter Toolbar not filtering rows when using a Formatter on a column

So in a current app, I have to use a custom Formatter on a couple rows in my jqGrid. All these do is take a few fields from my ajax call, concat them into one, and place that into a row.
EG ( data.toStreet + data.toCity + data.toState + data.toZip ) comes back as "Street City, State Zip" into the "To Address" column. This works fine and the data displays correctly, but when using the filtering toolbar, the filter is only based on the first val (data.street). below is a super simplified version of the pieces of code in question.
$('#grid').jqGrid({
...
colNames:["AddressTo", "AddressFrom"],
colModel:[
{name:"toStreet" formatter: ToAddressFormatter},
{name:"fromStreet" formatter: FromAddressFormatter}
],
...
}),
$('#grid').jqGrid('filterToolbar',
{
stringResult:true,
searchOnenter: true,
defaultSearch: 'cn'
}
});
ToAddressFormatter = function(el, opt, rowObj){
var address = rowObj.toStreet+ " " + rowObj.toCity + ", " + rowObj.toState + " " + rowObj.toZip;
return address;
},
FromAddressFormatter = function(el, opt, rowObj){
var address = rowObj.fromStreet+ " " + rowObj.fromCity + ", " + rowObj.fromState + " " + rowObj.fromZip;
return address;
}
So if the value in the cel says "123 fake st, springfield, Va 22344" after being formatted, the filter toolbar can only search on "123 fake st" and nothing else.
Does anybody have any clue on how to remedy this, or possibly why it's happening and a good workaround??
EDIT:
I have included the beginning of my grid. Also, the property Address of result.d is created in the code below, and not returned from the webservice. My column is mapped to "Address" which displays the formatting properly, but still does not search as intended.
$('#grdDisasters').jqGrid({
datatype: function(postdata) {
var obj = { "showActive": $('#btnFilterActive.pressed').length > 0 ? true : false, "showInactive": $('#btnFilterActive.pressed').length > 0 ? true : false,
'page': postdata.page, 'rows': postdata.rows, 'sortIndex': postdata.sidx, 'sortDirection': postdata.sord, 'search': postdata._search,
'filters': postdata.filters || ''
};
$.ajax({
url: "/GetGrid",
data: JSON.stringify(obj),
success: function(result) {
for (var i = 0, il = result.d.rows.length; i < il; i++) {
LoadedDisasters[i] = result.d.rows[i];
result.d.rows[i].cells.Address = result.d.rows[i].cells.Street + " " + result.d.rows[i].cells.City + ", "+ result.d.rows[i].cells.State+ " "+ result.d.rows[i].cells.Zip;
}
result.d = NET.format(result.d);//just correctly format dates
UpdateJQGridData($('#grdDisasters'), result.d);
},
error: function(result) {
//alert("Test failed");
}
});
jqGrid has a problem filtering rows when data is formatted using custom/predefined formatter.
You will have to filter rows on the server-side.
Add 2 more request parameter in your controller to handle jqgrid search request:
When jqGrid requests for filtered raws it will add a parameter: _search with value: true
and all the search parameter like col1=abc&col4=123 meaning user wanted to filter using column named col1 and column named col4 with values respectively: abc and 123
Use those values and query the database with like operation something as follows:
select id, concat(street1, street2, city, state, zip) as address
where address like "%abc%" and id like "%123%"
return these rows as json to jqGrid and display those in the current page. So basically you will have to have a jqGrid with server-side paging, sorting and searching. You can not use client-side paging, sorting and searching features. Also, make sure you don't have loadonce: true set.
I think that you fill the grid in the wrong way. If your source data has toStreet, toCity, toState, toZip, fromStreet, fromCity, fromState, fromZip properties and you need to have composed addressTo and addressFrom you should do this in another way. Your problem is that toStreet and fromStreet will be saved locally in the internal data parameter in the original format like you get it from the server. The local searching uses the data parameter, so the toStreet and fromStreet like you get there from the server will be used.
You don't posted more full code of jqGrid which you use. So I suppose that you use datatype: 'json', datatype: 'jsonp' or datatype: 'xml' in combination with loadonce: true. You should define colModel
$('#grid').jqGrid({
...
colNames:["AddressTo", "AddressFrom"],
colModel:[
{name: "addressTo", ...},
{name: "addressFrom", ...}
],
beforeProcessing: function (data) {
var i, rows = data.rows, l = rows.length, item;
for (i = 0; i < l; i++) {
item = rows[i];
item.addressTo = item.toStreet + " " + item.toCity + ", " +
item.toState + " " + item.toZip;
item.addressFrom = item.fromStreet+ " " + item.fromCity + ", " +
item.fromState + " " + item.fromZip;
}
}
...
});
The exact code depend on the format of the input data. The advantage of the usage of beforeProcessing is that it will be called before the data will be processed by jqGrid. So you can do any modification in the data or like in the above.
UPDATED: The code of datatype can be easy implemented in another way using standard jqGrid options. So I suggest to use the following settings:
datatype: "json",
url: "/GetGrid",
postData: {
// add and to the list of parameters sent to the web service
showActive: function () {
return $('#btnFilterActive.pressed').length > 0;
},
showInactive: function () {
return $('#btnFilterActive.pressed').length > 0;
}
},
prmNames: {
// rename some parameters sent to the web service
sort: "sortIndex",
order: "sortDirection",
search: "search",
// don't send nd parameter to the server
nd: null
// you leave the nd is you don't set any "Cache-Control" HTTP header
// I would recommend you to set "Cache-Control: private, max-age=0"
// For example
// HttpContext.Current.Response.Cache.SetMaxAge (new TimeSpan(0));
},
serializeGridData: function (postData) {
// control modification of the the data (parameters) which will be sent
// to the web method
if (typeof postData.filters === "undefined") {
postData.filters = "";
}
return JSON.stringify(postData);
},
ajaxGridOptions: { contentType: "application/json" },
jsonReader: {
root: "d.rows",
page: function (obj) { return obj.d.page; },
total: function (obj) { return obj.d.total; },
records: function (obj) { return obj.d.rows.length; },
repeatitems: false
},
loadError: function (jqXHR, textStatus, errorThrown) {
// see an implementation example in the answers
// https://stackoverflow.com/a/6969114/315935
// and
// https://stackoverflow.com/a/5501644/315935
},
colNames:["AddressTo", "AddressFrom"],
colModel:[
{name: "addressTo", ...},
{name: "addressFrom", ...}
],
beforeProcessing: function (data) {
var i, rows, l, item;
data.d = NET.format(data.d); // just correctly format dates
rows = data.d.rows;
l = rows.length;
for (i = 0; i < l; i++) {
item = rows[i];
LoadedDisasters[i] = item;
item.addressTo = item.toStreet + " " + item.toCity + ", " +
item.toState + " " + item.toZip;
item.addressFrom = item.fromStreet+ " " + item.fromCity + ", " +
item.fromState + " " + item.fromZip;
}
}
...
The usage of nd: null with setting of "Cache-Control: private, max-age=0" I described in the answer. You can download the corresponding demo project which use this. In general one needs just include one additional line where you call SetMaxAge
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public MyGridData GetGrid(...) {
HttpContext.Current.Response.Cache.SetMaxAge (new TimeSpan(0));
...
}
See more about caching control you can read here.

Resources