Passing Variable from JSON data - javascript

I am building a mobile app using Titanium for ios and I am having a tough time getting my arms wrapped around passing variables. I am using a combination of local database and remote database to deliver my data. In this case I want to pass the data on the tableViewRow selected. The label that displays the data I call "categorydescription". In my table.addEventListener, I want to pass that data as the title for the new window and I will pass that same data to my php file on the remote server. Here is the code I am trying to use:
var xhr = Ti.Network.createHTTPClient({
onload: function() {
Ti.API.debug(this.responseText);
var json = JSON.parse(this.responseText);
for (i = 0; i < json.cms_client.length; i++) {
client = json.cms_client[i];
row = Ti.UI.createTableViewRow({
height:'44dp',
hasChild:true
});
var categorydescription = Ti.UI.createLabel({
text:client.catdesc,
font:{fontSize:'16dp', fontWeight:'bold'},
height:'auto',
left:'10dp',
color:'#000'
});
row.add(categorydescription);
tableData.push(row);
}
table.addEventListener('click',function(e) {
var win = Ti.UI.createWindow({url: 'clients.js', title: ??});
var catdesc = ??;
win.catdesc = catdesc;
Titanium.UI.currentTab.open(win,{animated:true});
});
table.setData(tableData);
Would someone be so kind to tell me what I need to put in place of the ?? in the 'title' and 'var catdesc' above?

Just add the category description and title to the row object itself:
row = Ti.UI.createTableViewRow({
height:'44dp',
hasChild:true,
categoryDescription : client.catdesc, //Add this
clientTitle : client.title // Add this
});
Now get them in the listener:
table.addEventListener('click',function(e) {
var win = Ti.UI.createWindow({url: 'clients.js', title: e.row.title});
var catdesc = e.row.categoryDescription;
win.catdesc = catdesc;
Titanium.UI.currentTab.open(win,{animated:true});
});

Related

ServiceNow auto-populate Script not being called

I have a table in ServiceNow that contains Store and a corresponding Tier that is associated with the Store.
I am trying to auto-populate a record producer, once Store is selected. and my script is not running.
The table is a custom table created in a scoped application which is new to me so not sure what I am doing wrong in the scripting. Any advice?
//Catalog Client Script (runs on [Store] Record Producer Change)
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue == '') {
return;
}
// new GlideAjax object referencing store of AJAX script include
var ga = new GlideAjax("HRProfileAjax");
// add store parameter to define which function we want to call
// method store in script include will be getFavorites
ga.addParam("sysparm_store", "getHRProfile");
ga.addParam("sysparm_tier", "getHRProfile");
// submit request to server, call ajaxResponse function with server response
ga.getXML(ajaxResponse);
function ajaxResponse(serverResponse) {
// get result element and attributes
var result = serverResponse.responseXML.getElementsByTagstore("result");
var message = result[0].getAttribute("tier");
//check for message attribute and alert user
//if(message)
//alert(message);
//build output to display on client for testing
// get favorite elements
var favorites = serverResponse.responseXML.getElementsByTagstore("favorite");
for(var i = 0; i < favorites.length; i++) {
var store = favorites[i].getAttribute("store");
g_form.setValue(store);
var tier = favorites[i].getAttribute("tier");
//output += store + " = " + tier + "\n";
g_form.setValue(store,tier);
}
//g_form.setValue('number',output);
}
//Script #2 HR PROFILE AJAX
/*
* HRProfileAjax script include Description - sample AJAX processor returning multiple value pairs
*/
var HRProfileAjax = Class.create();
HRProfileAjax.prototype = Object.extendsObject(global.AbstractAjaxProcessor, {
/*
* method available to client scripts call using:
* var gajax = new GlideAjax("HRProfileAjax");
* gajax.addParam("sysparm_store", "getFavorites");
*/
getHRProfile : function() {
// build new response xml element for result
var result = this.newItem("result");
var store = this.getParameter('store');
var hrPro = new GlideRecord('x_hiring_gri_hr_storetier');
hrPro.addQuery('store',store);
hrPro.query();
if(hrPro.next()){
result.setAttribute("message", "returning all favorites");
this._addFavorite("tier", hrPro.tier);
}
},
_addFavorite : function(store, value) {
var favs = this.newItem("favorite");
favs.setAttribute("store", store);
},
type : "HRProfileAjax"
});

ServiceNow UI Page GlideAjax

I created a form using UI Page and am trying to have some fields autopopulated onChange. I have a client script that works for the most part, but the issue arises when certain fields need to be dot-walked in order to be autopopulated. I've read that dot-walking will not work in client scripts for scoped applications and that a GlideAjax code will need to be used instead. I'm not familiar with GlideAjax and Script Includes, can someone help me with transitioning my code?
My current client script looks like this:
function beneficiary_1(){
var usr = g_user.userID;
var related = $('family_member_1').value;
var rec = new GlideRecord('hr_beneficiary');
rec.addQuery('employee',usr);
rec.addQuery('sys_id',related);
rec.query(dataReturned);
}
function dataReturned(rec){
//autopopulate the beneficiary fields pending on the user selection
if(rec.next()) {
$('fm1_ssn').value = rec.ssn;
$('fm1_address').value = rec.beneficiary_contact.address;
$('fm1_email').value = rec.beneficiary_contact.email;
$('fm1_phone').value = rec.beneficiary_contact.mobile_phone;
var dob = rec.date_of_birth;
var arr = dob.split("-");
var date = arr[1] + "/"+ arr[2] + "/" + arr[0] ;
$('fm1_date_of_birth').value = date;
}
}
fm1_address, fm1_email, and fm1_phone do not auto populate because the value is dot walking from the HR_Beneficiary table to the HR_Emergency_Contact table.
How can I transform the above code to GlideAjax format?
I haven't tested this code so you may need to debug it, but hopefully gets you on the right track. However there are a couple of steps for this.
Create a script include that pull the data and send a response to an ajax call.
Call this script include from a client script using GlideAjax.
Handle the AJAX response and populate the form.
This is part of the client script in #2
A couple of good websites to look at for this
GlideAjax documentation for reference
Returning multiple values with GlideAjax
1. Script Include - Here you will create your method to pull the data and respond to an ajax call.
This script include object has the following details
Name: BeneficiaryContact
Parateters:
sysparm_my_userid - user ID of the employee
sysparm_my_relativeid - relative sys_id
Make certain to check "Client callable" in the script include options.
var BeneficiaryContact = Class.create();
BeneficiaryContact.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getContact : function() {
// parameters
var userID = this.getParameter('sysparm_my_userid');
var relativeID = this.getParameter('sysparm_my_relativeid');
// query
var rec = new GlideRecord('hr_beneficiary');
rec.addQuery('employee', userID);
rec.addQuery('sys_id', relativeID);
rec.query();
// build object
var obj = {};
obj.has_value = rec.hasNext(); // set if a record was found
// populate object
if(rec.next()) {
obj.ssn = rec.ssn;
obj.date_of_birth = rec.date_of_birth.toString();
obj.address = rec.beneficiary_contact.address.toString();
obj.email = rec.beneficiary_contact.email.toString();
obj.mobile_phone = rec.beneficiary_contact.mobile_phone.toString();
}
// encode to json
var json = new JSON();
var data = json.encode(obj);
return data;
},
type : "BeneficiaryContact"
});
2. Client Script - Here you will call BeneficiaryContact from #1 with a client script
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
var usr = g_user.userID;
var related = $('family_member_1').value;
var ga = new GlideAjax('BeneficiaryContact'); // call the object
ga.addParam('sysparm_name', 'getContact'); // call the function
ga.addParam('sysparm_my_userid', usr); // pass in userID
ga.addParam('sysparm_my_relativeid', related); // pass in relative sys_id
ga.getXML(populateBeneficiary);
}
3. Handle AJAX response - Deal with the response from #2
This is part of your client script
Here I put in the answer.has_value check as an example, but you may want to remove that until this works and you're done debugging.
function populateBeneficiary(response) {
var answer = response.responseXML.documentElement.getAttribute("answer");
answer = answer.evalJSON(); // convert json in to an object
// check if a value was found
if (answer.has_value) {
var dob = answer.date_of_birth;
var arr = dob.split("-");
var date = arr[1] + "/"+ arr[2] + "/" + arr[0];
$('fm1_ssn').value = answer.ssn;
$('fm1_address').value = answer.address;
$('fm1_email').value = answer.email;
$('fm1_phone').value = answer.mobile_phone;
$('fm1_date_of_birth').value = date;
}
else {
g_form.addErrorMessage('A beneficiary was not found.');
}
}

Show all objects present in localStorage on a webpage

I am storing my data from a form in localstorage in the following format:
Object {title: "dsadasds", dueDate: "dsadasdsa", summary: "dsadadas", body: "dasdasdas"}
Object {title: "dasdadsa", dueDate: "dasdasdadasda", summary: "dsadasdasd", body: "dasdasdas"}
This data is stored in localstorage every time a user submits the form. Now in a different page 'localhost:3000/notes' i wanna show all these objects stored in localStorage. Currently with the following code, its just showing the last object submitted.
var form = $('#form'),
formTitle = $('#title'),
formDueDate = $('#dueDate'),
formSummary = $('#summary'),
formBody = $('#body');
var title = formTitle.val();
var dueDate = formDueDate.val();
var summary = formSummary.val();
var body = formBody.val();
var newContent2 = $('#new-content2')
var test = {};
test = {
title: title,
dueDate: dueDate,
summary: summary,
body: body
}
localStorage.setItem('test', JSON.stringify(test));
var LocalStoredData = JSON.parse(localStorage.getItem('test'));
console.log(LocalStoredData);
//for retrieving data from locastorage
var retrievedData = localStorage.getItem('test');
var text = JSON.parse(retrievedData);
var showTitle = text["title"];
var showDueDate= text["dueDate"];
var showSummary = text["summary"];
var showBody = text["body"];
$('#showTitle').html(showTitle);
$('#showDueDate').html(showDueDate);
$('#showSummary').html(showSummary);
$('#showBody').html(showBody);
I need to loop trough all the objects (or any other mechanism) to extract all the objects from localStorage and display them in appropriate div on the web page. I tried putting the retrieval code in the loop:
for(var i=0;i<localStorage.length;i++)
but using this loop its not showing anything. How can I show all the objects present in my localStorage.
You're looking for
for (var i=0; i<localStorage.length; i++) {
var key = localStorage.key(i);
var item = localStorage.getItem(key);
try {
item = JSON.parse(item);
} catch(e) {
console.log(key+" is not in JSON format");
}
…
}
You can also easily get all the contents of LocalStorage using Object.keys:
Object.keys(localStorage).forEach(key => {
console.log(key, localStorage.getItem(key))
})

How to retrieve multi-value Taxonomy Field from term store SharePoint online

I am trying to retrieve terms from term store using JavaScript, it work just a fine with this code:
Get the label of single taxonomy field:
var fieldValue = item.get_item("FieldName");
var fieldLabel = fieldValue.Label;
I have one issue to retrieve labels of a multi-value Taxonomy Field?
I've tried this
var fieldValue = item.get_item("FieldName");
var taxEnumerator = fieldValue.getEnumerator();
while(taxEnumerator.moveNext()){
var currentTerm = taxEnumerator.get_current();
var label = currentTerm.Label;
// do something with the label here
}
But it doesn't work
Most likely you are getting this error since sp.taxonomy.js library has not been loaded and in that case taxonomy field value is returned as "lightweight" object (not of SP.Taxonomy.TaxonomyFieldValueCollection object type).
Option 1 (recommended): getting getting multiple taxonomy field values with sp.taxonomy library
First of all, I would recommend this approach since SP.Taxonomy namespace provides not only a standard way for dealing with taxonomy field values but also a way of working with Managed Metadata API via JSOM.
The following example shows how to:
ensure sp.taxonomy.js library has been loaded
get multiple taxonomy field value which represents
SP.Taxonomy.TaxonomyFieldValueCollection object
Example:
SP.SOD.registerSod('sp.taxonomy.js', SP.Utilities.Utility.getLayoutsPageUrl('sp.taxonomy.js'));
SP.SOD.executeFunc('sp.taxonomy.js', 'SP.Taxonomy.TaxonomySession', function () {
var ctx = SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle(listTitle);
var item = list.getItemById(itemId);
ctx.load(item);
ctx.executeQueryAsync(
function(){
var fieldVal = item.get_item(fieldName);
for(var i = 0; i < fieldVal.get_count(); i++) {
var label = fieldVal.get_item(i).get_label();
var guid = fieldVal.get_item(i).get_termGuid();
//...
}
},
function(sender,args){
console.log(args.get_message());
});
});
Option 2: getting multiple taxonomy field values without sp.taxonomy.js library loaded
When sp.taxonomy library is not loaded, taxonomy field value could still be retrieved via _Child_Items_ property as demonstrated below:
var ctx = SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle(listTitle);
var item = list.getItemById(itemId);
ctx.load(item);
ctx.executeQueryAsync(
function(){
var fieldVal = item.get_item(fieldName)._Child_Items_;
for(var i = 0; i < fieldVal.length; i++) {
var label = fieldVal[i].Label;
var guid = fieldVal[i].TermGuid;
//...
}
},
function(sender,args){
console.log(args.get_message());
});

AngularJS Array Not Loading On View Load, but Alerts/Console Work

I am trying to push values into an array as follows, but it is showing as an empty array. Alerting works. I am sure I am missing something obvious. Any clues? I have included the code with the just the array push attempt and another entry of code that has working alerts.
$scope.termsArray = [];
execOperation();
function execOperation() {
//Current Context
var context = SP.ClientContext.get_current();
//Current Taxonomy Session
var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);
//Term Stores
var termStores = taxSession.get_termStores();
//Name of the Term Store from which to get the Terms.
var termStore = termStores.getByName("Taxonomy_111111111111");
//GUID of Term Set from which to get the Terms.
var termSet = termStore.getTermSet("12345-55-689");
var terms = termSet.getAllTerms();
context.load(terms);
context.executeQueryAsync(function () {
var termEnumerator = terms.getEnumerator();
while (termEnumerator.moveNext()) {
var currentTerm = termEnumerator.get_current();
$scope.termsArray.push({
termName: currentTerm.get_name(),
termGUID: currentTerm.get_id(),
termSynonyms: 'Coming Soon'
});
}
}, function (sender, args) {
console.log(args.get_message());
});
}
Here is the code with working alerts:
function execOperation() {
//Current Context
var context = SP.ClientContext.get_current();
//Current Taxonomy Session
var taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context);
//Term Stores
var termStores = taxSession.get_termStores();
//Name of the Term Store from which to get the Terms.
var termStore = termStores.getByName("Taxonomy_111111111111");
//GUID of Term Set from which to get the Terms.
var termSet = termStore.getTermSet("12345-55-689");
var terms = termSet.getAllTerms();
context.load(terms);
context.executeQueryAsync(function () {
var termEnumerator = terms.getEnumerator();
var termList = "Terms: \n";
while (termEnumerator.moveNext()) {
var currentTerm = termEnumerator.get_current();
$scope.termsArray.push({
termName: currentTerm.get_name(),
termGUID: currentTerm.get_id(),
termSynonyms: 'Coming Soon'
});
termList += currentTerm.get_id() + currentTerm.get_name() + "\n";
}
alert(termList);
}, function (sender, args) {
console.log(args.get_message());
});
}
Here is the HTML output:
<div> {{termsArray}}</div>
It returns []
Update: If I click in an input box and back out, or click an alert and hit ok, it then loads the array instead of loading on page load.
I was able to track the issue down. It appears that Angular doesn't respect non-Angular functions on load, so I needed to wrap the $scoped array in a $scope.apply. Please see here for details: Execute SharePoint Function On Page Load in AngularJS Application ($scope issue???)

Categories

Resources