Wordpress Woocommerce - Send order data to GoogleSheets via Webhooks - wordpress

So I wrote this code and it is not working as it should, it is pulling data from woocommerce Webhook with a "code.gs" code in GoogleSheets.
Problem is, if var product_name = myData.line_items[1].name; (and [2], [3] and [4].... and others) does not exist, the code does not work in GoogleSheets...
What i would like to achieve is, when i have two products in an order (myData.line_items[1].name exists, myData.line_items[2].name exists,...) that GoogleSheets would make a new line with that data for each one of the products.
function doGet(e) {
return HtmlService.createHtmlOutput("request received");
}
function doPost(e) {
var myData = JSON.parse([e.postData.contents]);
var order_number = myData.number;
var order_created = myData.date_created;
var product_name = myData.line_items[0].name;
var product_qty = myData.line_items[0].quantity;
var product_total = myData.line_items[0].total;
var produktsku = myData.line_items[0].sku;
var product_name = myData.line_items[1].name;
var product_qty = myData.line_items[1].quantity;
var product_total = myData.line_items[1].total;
var produktsku = myData.line_items[1].sku;
var product_namea = myData.line_items[2].name;
var product_qtya = myData.line_items[2].quantity;
var product_totala = myData.line_items[2].total;
var produktskua = myData.line_items[2].sku;
var product_nameb = myData.line_items[3].name;
var product_qtyb = myData.line_items[3].quantity;
var product_totalb = myData.line_items[3].total;
var produktskub = myData.line_items[3].sku;
var product_namec = myData.line_items[4].name;
var product_qtyc = myData.line_items[4].quantity;
var product_totalc = myData.line_items[4].total;
var produktskuc = myData.line_items[4].sku;
var product_named = myData.line_items[5].name;
var product_qtyd = myData.line_items[5].quantity;
var product_totald = myData.line_items[5].total;
var produktskud = myData.line_items[5].sku;
var order_total = myData.total;
var billing_email = myData.billing.email;
var billing_first_name = myData.billing.first_name;
var billing_last_name = myData.billing.last_name;
var billing_countryshort = myData.billing.country;
var payment_method = myData.payment_method_title;
var shipping_method = myData.shipping_lines[0].method_title;
var shipping_total = myData.shipping_lines[0].total;
var shipping_total = myData.shipping_lines[0].total;
var klingi = "1";
var timestamp = new Date();
var sheet = SpreadsheetApp.getActiveSheet();
sheet.appendRow([timestamp,order_created,order_number,product_name,produktsku,product_qty,product_total,order_total,billing_email,billing_first_name,billing_last_name,payment_method,shipping_method,shipping_total,billing_countryshort]);
if( produktskua ) {
sheet.appendRow(["Izdelek 2", "",order_number,product_namea,produktskua,product_qtya,product_totala]);
};
if( produktskub ) {
sheet.appendRow(["Izdelek 3", "",order_number,product_nameb,produktskub,product_qtyb,product_totalb]);
};
if( produktskuc ) {
sheet.appendRow(["Izdelek 4", "",order_number,product_namec,produktskuc,product_qtyc,product_totalc]);
};
}
Any ideas?
It stops working, even if I wrap it, it works only if value exists...
if( myData.line_items[1].name ) {
var product_namea = myData.line_items[1].name;
var product_qtya = myData.line_items[1].quantity;
var product_totala = myData.line_items[1].total;
var produktskua = myData.line_items[1].sku;
};

When assigning your post data to variables, you can use the ternary operator
This allows you to verify either a certain postData exists, and if not - assign an empty string to the variable in order to prevent problems with Google Sheets.
Syntax:
condition ? exprIfTrue : exprIfFalse
Sample:
var product_namea = (myData.line_items[2].name) ? myData.line_items[2].name : " ";
Also: Be careful with overwriting variable names, in your code you
have e.g. twice var product_name

Is solved like this:
function doPost(e) {
var myData = JSON.parse([e.postData.contents]);
var timestamp = new Date();
var order_created = myData.date_created;
var billing_first_name = myData.billing.first_name;
var billing_phone = myData.billing.phone;
var billing_email = myData.billing.email;
var shipping_address = myData.billing.address_1 + myData.billing.address_2;
var order_total = myData.total;
var order_number = myData.number;
var billing_last_name = myData.billing.last_name;
var billing_countryshort = myData.billing.country;
var payment_method = myData.payment_method_title;
var shipping_method = myData.shipping_lines[0].method_title;
var shipping_total = myData.shipping_lines[0].total;
var quantity_prvi = myData.line_items[0].quantity;
var linetotal_prvi = myData.line_items[0].total;
var produktsku_prvi = myData.line_items[0].sku;
var sheet = SpreadsheetApp.getActiveSheet();
sheet.appendRow([billing_countryshort,timestamp,order_created,"Order",order_number,billing_first_name,billing_last_name,shipping_address,billing_email,billing_phone,produktsku_prvi,quantity_prvi,linetotal_prvi,shipping_total,shipping_method,order_total,payment_method]);
var lineitems=""
for (i in myData.line_items)
if(i>0){
{
var quantity = myData.line_items[i].quantity;
var linetotal = myData.line_items[i].total;
var produktsku = myData.line_items[i].sku;
var sheet = SpreadsheetApp.getActiveSheet();
sheet.appendRow([billing_countryshort,timestamp,order_created,"Dodaten produkt",order_number,"","","","","",produktsku,quantity,linetotal]);
}
}
}

Related

Trouble integrating Woocommerce order details into Google Sheet with Google App Script API

I have an API that automatically pulls new order details from my Woocommerce store into a Google Sheet. It seems to be working however, it has failed to pull the first 7 orders into my google sheet. It has all of the orders after the first 7. How do I get it to pull the first 7 orders into the sheet?
Here is my Google App Script:
function start_sync() {
// Followed instructions at https://github.com/mithunmanohar/woocommerce-orders-google-sheets-integration
var sheet_name = "OrderDetails"
update_order_5_min(sheet_name)
}
function update_order_5_min(sheet_name) {
var ck = "ck_ed82fae51e5bafce28dde95224db9c9c4bd36dba";
var cs = "cs_9a16fd7b641769a65412f336de3e7a928f7e153c";
var website = "https://www.funtrackdayz.com";
var now = new Date();
var website_t ="240";
var min = website_t * 60
now.setMinutes(now.getMinutes() - min);
var n = now.toISOString();
var surl = website + "/wc-api/v3/orders?consumer_key=" + ck + "&consumer_secret=" + cs + "&status=processing&filter[created_at_min]=" + n //"&after=2016-10-27T10:10:10Z"
// var surl = website + "/wc-api/v3/orders?consumer_key=" + ck + "&consumer_secret=" + cs + "&status=processing"
// &filter[created_at_min]=" + n //"&after=2016-10-27T10:10:10Z"
var url = surl
var options = {
"method": "GET",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"muteHttpExceptions": true,
};
var result = UrlFetchApp.fetch(url, options);
if (result.getResponseCode() == 200) {
var params = JSON.parse(result.getContentText());
}
var doc = SpreadsheetApp.getActiveSpreadsheet();
var temp = doc.getSheetByName(sheet_name);
var consumption = {}
//"orders"
arrayLength = params["orders"].length
for (var i = 0; i < arrayLength; i++) {
var container = [];
a = container.push(params["orders"][i]["billing_address"]["first_name"]);
a = container.push(params["orders"][i]["billing_address"]["last_name"]);
a = container.push(params["orders"][i]["billing_address"]["address_1"] + ", " + params["orders"][i]["billing_address"]["address_2"]);
a = container.push("");
a = container.push(params["orders"][i]["billing_address"]["city"]);
a = container.push(params["orders"][i]["billing_address"]["state"]);
a = container.push(params["orders"][i]["billing_address"]["postcode"]);
a = container.push(params["orders"][i]["billing_address"]["phone"]);
a = container.push(params["orders"][i]["billing_address"]["email"]);
a = container.push(params["orders"][i]["total"]); //price
a = container.push(params["orders"][i]["payment_details"]["method_id"]);
c = params["orders"][i]["line_items"].length;
items = "";
skus="";
for (var k = 0; k < c; k++) {
item = params["orders"][i]["line_items"][k]["name"];
qty = params["orders"][i]["line_items"][k]["quantity"];
sku = params["orders"][i]["line_items"][k]["sku"];
meta = ""
try {
meta = params["orders"][i]["line_items"][k]["meta"][0]["value"];
meta = " - " + meta
} catch (err) {
meta = ""
}
item_f = qty + " x " + item + meta
items = items + item_f + ",\n"
skus = skus + ",\n"
}
a = container.push(items)
a = container.push(sku)
// a = container.push(params["orders"][i]["total_line_items_quantity"]); // Quantity
a = container.push(params["orders"][i]["order_number"]); //
a = container.push(params["orders"][i]["note"])
a = container.push(params["orders"][i]["created_at"]);
var doc = SpreadsheetApp.getActiveSpreadsheet();
var temp = doc.getSheetByName(sheet_name);
temp.appendRow(container);
removeDuplicates(sheet_name)
}
}
function removeDuplicates(sheet_name) {
var doc = SpreadsheetApp.getActiveSpreadsheet();
var sheet = doc.getSheetByName(sheet_name);
var data = sheet.getDataRange().getValues();
var newData = new Array();
for (i in data) {
var row = data[i];
var duplicate = false;
for (j in newData) {
if (row.join() == newData[j].join()) {
duplicate = true;
}
}
if (!duplicate) {
newData.push(row);
}
}
sheet.clearContents();
sheet.getRange(1, 1, newData.length, newData[0].length).setValues(newData);
}

EPPlus ColumnStacked chart data point colors

I am able to generate Column Stacked chart using EPPlus. There is is requirement to change the color of datapoint.
I found the solution of at enter link description here but it only changes the color of first datapoint of the series. Can I get help to change the color of other datapoints as well. Here is the concept that I am looking for enter image description here
Here is the function that helps to change datapoint first color
public void SetDataPointStyle(OfficeOpenXml.Drawing.Chart.ExcelChart chart, ExcelChartSerie series, int totalDataPoint, Color color)
{
var i = 0;
var found = false;
foreach (var s in chart.Series)
{
if (s == series)
{
found = true;
break;
}
++i;
}
if (!found) throw new InvalidOperationException("series not found.");
var nsm = chart.WorkSheet.Drawings.NameSpaceManager;
var nschart = nsm.LookupNamespace("c");
var nsa = nsm.LookupNamespace("a");
var node = chart.ChartXml.SelectSingleNode(#"c:chartSpace/c:chart/c:plotArea/c:barChart/c:ser[c:idx[#val='" + i.ToString(System.Globalization.CultureInfo.InvariantCulture) + "']]", nsm);
var doc = chart.ChartXml;
var spPr = doc.CreateElement("c:spPr", nschart);
var solidFill = spPr.AppendChild(doc.CreateElement("a:solidFill", nsa));
var srgbClr = solidFill.AppendChild(doc.CreateElement("a:srgbClr", nsa));
var valattrib = srgbClr.Attributes.Append(doc.CreateAttribute("val"));
valattrib.Value = ToHex(color).Substring(1);
//var ln = spPr.AppendChild(doc.CreateElement("a:ln", nsa));
//var lnSolidFill = ln.AppendChild(doc.CreateElement("a:solidFill", nsa));
//var lnSrgbClr = lnSolidFill.AppendChild(doc.CreateElement("a:srgbClr", nsa));
//var lnValattrib = lnSrgbClr.Attributes.Append(doc.CreateAttribute("val"));
//lnValattrib.Value = ToHex(Color.Gray).Substring(1);
node.AppendChild(spPr);
}
public String ToHex(Color c)
{
return "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");
}
SetDataPointStyle(chart, chart.Series[0], 1, Color.Tan);
You have to populate a series of data point colors per series. Here is an extension method that will set the series data points to random colors. Just have to specify the serie number. If pick your own colors just override the logic or send in an array to use:
public static void SetChartPointRandomColors(this ExcelChart chart, int serieNumber)
{
var chartXml = chart.ChartXml;
var nsa = chart.WorkSheet.Drawings.NameSpaceManager.LookupNamespace("a");
var nsuri = chartXml.DocumentElement.NamespaceURI;
var nsm = new XmlNamespaceManager(chartXml.NameTable);
nsm.AddNamespace("a", nsa);
nsm.AddNamespace("c", nsuri);
var serieNode = chart.ChartXml.SelectSingleNode(#"c:chartSpace/c:chart/c:plotArea/c:barChart/c:ser[c:idx[#val='" + serieNumber + "']]", nsm);
var serie = chart.Series[serieNumber];
var points = serie.Series.Length;
var rand = new Random(serieNumber);
for (var i = 1; i <= points; i++)
{
var dPt = chartXml.CreateNode(XmlNodeType.Element, "dPt", nsuri);
var idx = chartXml.CreateNode(XmlNodeType.Element, "idx", nsuri);
var att = chartXml.CreateAttribute("val", nsuri);
att.Value = i.ToString();
idx.Attributes.Append(att);
dPt.AppendChild(idx);
var srgbClr = chartXml.CreateNode(XmlNodeType.Element, "srgbClr", nsa);
att = chartXml.CreateAttribute("val");
//Generate a random color - override with own logic to specify
var color = Color.FromArgb(rand.Next(256), rand.Next(256), rand.Next(256));
att.Value = $"{color.R:X2}{color.G:X2}{color.B:X2}";
srgbClr.Attributes.Append(att);
var solidFill = chartXml.CreateNode(XmlNodeType.Element, "solidFill", nsa);
solidFill.AppendChild(srgbClr);
var spPr = chartXml.CreateNode(XmlNodeType.Element, "spPr", nsuri);
spPr.AppendChild(solidFill);
dPt.AppendChild(spPr);
serieNode.AppendChild(dPt);
}
}
Here is an example of usage:
[TestMethod]
public void Chart_BarChart_Colors_Test()
{
//Throw in some data
var datatable = new DataTable("tblData");
datatable.Columns.AddRange(new[]{new DataColumn("Col1", typeof(int)),new DataColumn("Col2", typeof(int)),new DataColumn("Col3", typeof(int))});
for (var i = 0; i < 10; i++){var row = datatable.NewRow();row[0] = i;row[1] = i * 10;row[2] = i * 15;datatable.Rows.Add(row);}
//Create a test file
var fileInfo = new FileInfo(#"c:\temp\Chart_BarChart_Colors.xlsx");
if (fileInfo.Exists)
fileInfo.Delete();
using (var pck = new ExcelPackage(fileInfo))
{
var workbook = pck.Workbook;
var worksheet = workbook.Worksheets.Add("Sheet1");
worksheet.Cells.LoadFromDataTable(datatable, true);
var chart = worksheet.Drawings.AddChart("chart test", eChartType.ColumnStacked);
chart.Series.Add(worksheet.Cells["B2:B11"], worksheet.Cells["A2:A11"]);
chart.Series.Add(worksheet.Cells["C2:C11"], worksheet.Cells["A2:A11"]);
chart.SetChartPointRandomColors(0);
chart.SetChartPointRandomColors(1);
pck.Save();
}
}
Will give you this:
I had a similar use case, I needed to set the color of a slice (datapoint) of a doughnut chart. This question/answer helped immensely and I figured I would share the result in case anyone else hits this issue.
Note 1: I am using C# 9 with nullability enabled; you can remove the !'s if you aren't using nullability.
Note 2: I have no use case for multiple series in a doughnut chart, so this is hardcoded to series 0. You can parameterize the SelectSingleNode index if this doesn't work for you.
public void SetDoughnutChartDataPointFill(ExcelChart chart, int dataPointIdx, Color color)
{
var nsm = chart.WorkSheet.Drawings.NameSpaceManager;
var nschart = nsm.LookupNamespace("c");
var nsa = nsm.LookupNamespace("a");
var node = chart.ChartXml.SelectSingleNode(#"c:chartSpace/c:chart/c:plotArea/c:doughnutChart/c:ser[c:idx[#val='0']]", nsm)!;
var doc = chart.ChartXml;
var dPt = doc.CreateElement("c:dPt", nschart);
var cdpIdx = doc.CreateElement("c:idx", nschart);
var valattr = cdpIdx.Attributes!.Append(doc.CreateAttribute("val"));
valattr.Value = dataPointIdx.ToString();
dPt.AppendChild(cdpIdx);
var spPr = doc.CreateElement("c:spPr", nschart);
var solidFill = spPr.AppendChild(doc.CreateElement("a:solidFill", nsa))!;
var srgbClr = solidFill.AppendChild(doc.CreateElement("a:srgbClr", nsa))!;
var valattrib = srgbClr.Attributes!.Append(doc.CreateAttribute("val"));
valattrib.Value = string.Format("{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B);
dPt.AppendChild(spPr);
node.AppendChild(dPt);
}

Google Sheets Google Analytics Data by Channel

I have a Google Sheets file which calls Google Analytics and pulls metrics. This works great. What I want to do is pull metrics by channel so that the far left column is a collection of channels (PPC, Display, Organic, Social, Email, Referral, Affiliate, Direct). Do I need to use the Multi-Channel Funnel setup? Or is there a better way to do this?
function getGAData() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("test Data");
// var startDate = dateToYMD(sheet.getRange(3,3).getValue());
// var endDate = dateToYMD(sheet.getRange(3,4).getValue());
var dateRanges = readDateRanges(sheet);
var profileIds = readProfileIds(sheet);
var GAMetrics = readGAMetrics(sheet);
var results = [];
var metrics = [];
var optArgs = [];
var filterCount = 0;
var prevFilter = '**NONE**';
var i, j, k;
var profileResults;
var tempResults;
for (i = 0; i < GAMetrics[0].length; i++) {
// Utilities.sleep(100);
if (prevFilter != GAMetrics[1][i]) {
metrics[filterCount] = GAMetrics[0][i];
optArgs[filterCount] = {
'start-index': '1',
'max-results': '10' // Display the first 250 results.
};
if (GAMetrics[1][i] != '')
optArgs[filterCount].filters = GAMetrics[1][i];
if (GAMetrics[2][i] != '')
optArgs[filterCount].segment = GAMetrics[2][i];
filterCount++;
} else {
metrics[filterCount-1] = metrics[filterCount-1] + ',' + GAMetrics[0][i];
}
prevFilter = GAMetrics[1][i];
}
for (i = 0; i < profileIds.length; i++) { // get GA data for each of the rows of input
profileResults = [];
var tableId = 'ga:' + profileIds[i][0];
var startDate = dateToYMD(dateRanges[i][0]);
var endDate = dateToYMD(dateRanges[i][1]);
for (j = 0; j < metrics.length; j++) {
var metric = metrics[j];
var options = optArgs[j];
//var options = {
// 'dimensions': 'ga:source',
//};
try {
// Make a request to the API.
tempResults = Analytics.Data.Ga.get(
'ga:' + profileIds[i][0], // Table id (format ga:xxxxxx).
dateToYMD(dateRanges[i][0]), // Start-date (format yyyy-MM-dd).
dateToYMD(dateRanges[i][1]), // End-date (format yyyy-MM-dd).
metrics[j], // Comma seperated list of metrics.
optArgs[j]);
var report = Analytics.Data.Ga.get(tableId, startDate, endDate, metric,
options);
if (typeof tempResults.getRows() != 'undefined')
appendArray(profileResults, tempResults.getRows()[0]);
} catch (e) {
Logger.log(e + ' - Profile ID: ' + profileIds[i][0] + ' - Metrics: ' + metrics[j] );
}
}
//append Profile results to the set
for (k = profileResults.length; k < GAMetrics[0].length; k++)
profileResults[k] = '0';
results.push(profileResults);
// Utilities.sleep(200);
}
sheet.getRange(6, 13, results.length, GAMetrics[0].length).setValues(results); // populate results on spreadsheet
emailLog('don#test.com','startDate');
}
function readDateRanges(sheet){
var rowStart = 6;
var columnStart = 1;
var numRows = sheet.getLastRow() - rowStart + 1;
return sheet.getRange(rowStart, columnStart, numRows, 2).getValues();
}
function readProfileIds(sheet) {
var rowStart = 6;
var columnStart = 3;
var numRows = sheet.getLastRow() - rowStart + 1;
return sheet.getRange(rowStart, columnStart, numRows, 1).getValues();
}
function readGAMetrics(sheet) {
var rowStart = 2;
var columnStart = 13;
var numColumns = sheet.getLastColumn() - columnStart + 1;
return sheet.getRange(rowStart, columnStart, 3, numColumns).getValues();
}
function dateToYMD(date) {
var d = date.getDate();
var m = date.getMonth() + 1;
var y = date.getFullYear();
return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
}
function appendArray(a1,a2) {
var startSize = a1.length;
for (var i = 0; i < a2.length; i++)
a1[startSize + i] = a2[i];
}
function emailLog(emailAddress,reportDate) {
var recipient = emailAddress; // Session.getActiveUser().getEmail();
var subject = 'GA Data Pull - extract for ' + reportDate;
var body = Logger.getLog();
MailApp.sendEmail(recipient, subject, body);
}

Swift link in a Annotation -> Webview

I try to find a way to add a link to a Annotation in Swift MapFramework, this link should forward the user to a WebView, as far i see i can't find any way to add a "touchable" link into a Annotations SubTitle
Here is my Code yet
class CustomPointAnnotation: MKPointAnnotation {
var imageName: String!
}
var info1 = CustomPointAnnotation()
info1.coordinate = CLLocationCoordinate2DMake(42, -84)
info1.title = "Info1"
info1.subtitle = "Subtitle"
info1.imageName = "1.png"
var info2 = CustomPointAnnotation()
info2.coordinate = CLLocationCoordinate2DMake(32, -95)
info2.title = "Info2"
info2.subtitle = "Subtitle"
info2.imageName = "2.png"
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if !(annotation is CustomPointAnnotation) {
return nil
}
let reuseId = "test"
var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
if anView == nil {
anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
anView.canShowCallout = true
}
else {
anView.annotation = annotation
}
//Set annotation-specific properties **AFTER**
//the view is dequeued or created...
let cpa = annotation as CustomPointAnnotation
anView.image = UIImage(named:cpa.imageName)
return anView
}
Is there maybe a way to use the UIGestureRecognizer for this?
I already tried it like
var longpress = UILongPressGestureRecognizer(target: self, action: "newInformation:")
longpress.minimumPressDuration = 2.0
info1.addGestureRecognizer(longpress)
But ending with "ViewController.CustomPointAnnotation does not have a member named addGestureRecognizer"
Here is a working solution
override func viewDidLoad() {
super.viewDidLoad()
//1
var lat1:CLLocationDegrees = 40.748708
var long1:CLLocationDegrees = -73.985643
var latDelta1:CLLocationDegrees = 0.01
var longDelta1:CLLocationDegrees = 0.01
var span1:MKCoordinateSpan = MKCoordinateSpanMake(latDelta1, longDelta1)
var location1:CLLocationCoordinate2D = CLLocationCoordinate2DMake(lat1, long1)
var region1:MKCoordinateRegion = MKCoordinateRegionMake(location1, span1)
Map.setRegion(region1, animated: true)
var info1 = CustomPointAnnotation()
info1.coordinate = location1
info1.title = "Test Title1!"
info1.subtitle = "Subtitle1"
info1.imageName = "1.png"
Map.addAnnotation(info1)
//2
var lat2:CLLocationDegrees = 41.748708
var long2:CLLocationDegrees = -72.985643
var latDelta2:CLLocationDegrees = 0.01
var longDelta2:CLLocationDegrees = 0.01
var span2:MKCoordinateSpan = MKCoordinateSpanMake(latDelta2, longDelta2)
var location2:CLLocationCoordinate2D = CLLocationCoordinate2DMake(lat2, long2)
var region2:MKCoordinateRegion = MKCoordinateRegionMake(location2, span2)
var info2 = CustomPointAnnotation()
info2.coordinate = location2
info2.title = "Test Title2!"
info2.subtitle = "Subtitle2"
info2.imageName = "2.png"
Map.addAnnotation(info2)
}
func mapView(mapView: MKMapView!, annotationView: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if control == annotationView.rightCalloutAccessoryView {
println("Disclosure Pressed! \(self.title)")
}
}
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if !(annotation is CustomPointAnnotation) {
return nil
}
let reuseId = "test"
var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
if anView == nil {
anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
anView.canShowCallout = true
anView.rightCalloutAccessoryView = UIButton.buttonWithType(.InfoDark) as UIButton
}
else {
anView.annotation = annotation
}
//Set annotation-specific properties **AFTER**
//the view is dequeued or created...
let cpa = annotation as CustomPointAnnotation
anView.image = UIImage(named:cpa.imageName)
return anView
}

Load SQLite query results into textarea in same View

How can you place results from a SQLite query into a textarea?
The idea is that the user presses the 'next' button and then the textarea displays the text for the next text value in the next record. I believe that I'm passing the values correctly, but when I use trace(), the values come up as undefined.
What am I doing wrong?
protected function button6_clickHandler(event:MouseEvent):void // pushed --> button
{
var cardNumber:int = parseInt(cardNumberLabel.text);
var newcardid:int = cardNumber+1;
var sqlresult:SQLResult = stmt.getResult();
stmt.sqlConnection = conn;
conn.open(File.applicationStorageDirectory.resolvePath("FlashCards.db"));
stmt.text = "SELECT * FROM cardItems WHERE id = ?";
stmt.parameters[0] = newcardid;
stmt.execute();
trace(sqlresult.data); // value = [object Object]
stext1.text = sqlresult.data.cSide1;
trace(sqlresult.data.cSide1); // value = 'undefined'
cardNumberLabel.text = sqlresult.data.id;
trace(sqlresult.data.id); // value = 'undefined'
conn.close();
moveEffectRPart1.play();
moveEffectRPart1.addEventListener(EffectEvent.EFFECT_END, nextMoveRPart);
}
EDIT: WORKING CODE*
private function nextMoveRPart(event:EffectEvent):void
{
var cardNumber:int = parseInt(cardNumberLabel.text);
stmt.sqlConnection = conn;
conn.open(File.applicationStorageDirectory.resolvePath("FlashCards.db"));
stmt.text = "SELECT * FROM cardItems WHERE id = ?" + "AND id <= MAX(id)";
stmt.parameters[0] = cardNumber+1;
stmt.addEventListener(SQLEvent.RESULT, resultHandlerPrev);
stmt.execute();
conn.close();
moveEffectRPart2.play();
}
function resultHandlerNext(event:SQLEvent):void // result handler next
{
var result:SQLResult = stmt.getResult();
var numResults:int = result.data.length;
for(var i:int = 0; i < numResults; i++)
{
var row:Object = result.data[i];
stext1.text = row.cSide1;
stext2.text = row.cSide2;
cardNumberLabel.text = row.id;
}
}

Resources