Retrieve objectId in Parse - javascript

In simple, I am trying to retrieve the objectId for a particular user in parse (using Javascript). I can retrieve any other query in the database, such as username, phone, mailing address but not the objectId, here is how I retrieve the rest of the query:
var objectId = userInfo.get("objectId");
Any assistance would be greatly appreciated.
Below is more lines of the code (everything is retrieved beside objectId)
query.find({ success: function(array) {
// this means the query was a success, but we're not yet certain that we found anything
// the param to find's success is an array of PFObjects, possibly empty
if (array.length > 0) {
var userInfo = array[0];
var address = userInfo.get("address");
$scope.address = address;
var email = userInfo.get("username");
$scope.email = email;
var fullName = userInfo.get("fullName");
$scope.fullName= fullName;
var number = userInfo.get("phoneNumber");
$scope.number= number;
var objectId = userInfo.get("objectId");
$scope.objectId= objectId;
var mailingAddress = userInfo.get("mailingAddress");
$scope.mailingAddress = mailingAddress;
var plan = userInfo.get("plan");
$scope.plan = plan;
Thanks in advance

The js sdk provides an id member, so ...
$scope.objectId = userInfo.id;
As an aside, check out the JS guide on their site. It's a very well written doc. Pay particular attention to the code snippets in the objects and query sections.

Related

Apps Script: Get user input from HTML form and save them as global variables

The server side script below receives user input from an HTML form and adds these user data/input to the last available row of my Google Sheet. It´s been working pretty fine. But now I want to store some elements of the array that is in this script as global variables, so that I can re-use them later on in other server side functions bound to the same Google Sheet. I am specifically interested in the values inside lastName, email and phone. Any idea how this can be done?
Thank you so much in advance for your hints and help.
function AddUserInputToSheet(gender, firstName, lastName, age, email, phone) {
var url = 'SHEET_URL';
var ss = SpreadsheetApp.openByUrl(url);
var webAppSheet = ss.getSheetByName("SHEET_NAME");
webAppSheet.appendRow([gender, firstName, lastName, age, email, phone]);
}
You can use Properties Service of Apps Script.
This service allows scripts to store strings as key-value pairs scoped
to one script, one user of a script, or one document in which an
editor add-on is used.
In your case, there are 2 options you can choose. Script Properties and User Properties.
The difference between the two is the content of Script Properties are shared to all users while User Properties is only available to the current user of a script, add-on, or web app.
Here I created an example of how to use Properties.
function setProperties(lastName = "Test Last Name", email = "Test Email", phone = "Test Phone"){
var scriptProperties = PropertiesService.getScriptProperties();
scriptProperties.setProperties({'lastName': lastName, 'email': email, 'phone':phone})
}
function readProperties(){
var scriptProperties = PropertiesService.getScriptProperties();
Logger.log(scriptProperties.getProperties());
}
Here I run the readProperties() function first and the result is
Then I run the 'setProperties()' and rerun the readProperties() function again:
I reload the script page and ran the readProperties() function:
To add it in your script, you can set the properties in AddUserInputToSheet() and call it anywhere in your script.
Example:
function AddUserInputToSheet(gender, firstName, lastName, age, email, phone) {
var url = 'SHEET_URL';
var ss = SpreadsheetApp.openByUrl(url);
var webAppSheet = ss.getSheetByName("SHEET_NAME");
webAppSheet.appendRow([gender, firstName, lastName, age, email, phone]);
var scriptProperties = PropertiesService.getScriptProperties();
scriptProperties.setProperties({'lastName': lastName, 'email': email, 'phone':phone})
}
function someFunction(){
var scriptProperties = PropertiesService.getScriptProperties();
var data = scriptProperties.getProperties();
var lastName = data["lastName"];
var email = data["email"];
var phone = data["phone"];
//some operations here
}
Here's an example:
function myfunk1() {
PropertiesService.getScriptProperties().setProperty('Global1',JSON.stringify(SpreadsheetApp.getActive().getSheetByName('Sheet0').getDataRange().getDisplayValues()));
}
function myfunk2() {
const vs = JSON.parse(PropertiesService.getScriptProperties().getProperty('Global1'))
SpreadsheetApp.getActive().getSheetByName('Sheet1').getRange(1,1,vs.length,vs[0].length).setValues(vs);
}

Google Apps Script: How to set return to my page?

I'm using Google Apps Script to write values from a form to a Google Spreadsheet.
I have the form in my HTML page and its action calls the Google Apps Script to write in the sheet.
Now I'd like to go back to my site with a flag var and show a message (Error or Complete) based on the result of the function.
I know how to create and set the flag variable but I don't know how to "send" it to my page. I was only able to show my flag with something like this (that's the whole function I have in GAS)
function doPost(e){
var id = "";
var name = e.parameter['name'];
var surname = e.parameter['surname'];
var serial = e.parameter['serial'];
var eMail = e.parameter['email'];
var text = e.parameter['text'];
var date = new Date();
var ans = ""
var ctrl= "WIP";
var vals = [id, date, name, surname, serial, eMail, text, ans, flag];
var sheetObj =SpreadsheetApp.openById("myKey").getSheetByName('Requests').appendRow(vals);
return ContentService.createTextOutput(someOutput);
}
Someone knows how to do what I need?
Thanks a lot for your help!
S.
You can do something like this
return ContentService.createTextOutput("Complete").setMimeType(ContentService.MimeType.TEXT);
Or in case of exception return 'Error' from your catch block like this
return ContentService.createTextOutput("Error").setMimeType(ContentService.MimeType.TEXT);

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.');
}
}

parse.com : Inner query on an id column Not retrieving all columns I want

Parse class Schema :
Class name : balance
Columns : myid createdAt amount
Class name : tokens
Columns : myid registerUser isActiveToken
I want to retrieve amount, myid, registerUser, isActiveToken using parse.com javascript.
I am not able to get this using parse js refernce.
https://parse.com/docs/js/guide#queries
matchesKeyInQuery is giving a toJSOn error in parse js
var balance = Parse.Object.extend("balance");
var teamQuery = new Parse.Query(balance);
var userQuery = new Parse.Query("tokens");
userQuery.matchesKeyInQuery("amount", teamQuery); //I made a blunder here by not understanding matchesKeyInQuery
userQuery.find({
success: function(results) {
// results has the list of users with a hometown team with a winning record
}
});
matchesQuery is throwing a bad inner query error
var balance = Parse.Object.extend("balance");
var tokens = Parse.Object.extend("tokens");
var innerQuery = new Parse.Query(balance);
innerQuery.exists("amount");
var query = new Parse.Query(tokens);
query.matchesQuery("myid", innerQuery);
query.find({
success: function(comments) {
// tokens now contains the tokens for balance with amounts.
}
});
Overcame this through javascript merging(dirty way), would love to find something in Parse SDK
in the first query method matchesKeyInQuery accepts 3 arguments, first one is the key in the called query, the second one argument is the key in the passed query and third one is the passed query.
var balance = Parse.Object.extend("balance");
var tokens = Parse.Object.extend("tokens");
var teamQuery = new Parse.Query(balance);
var userQuery = new Parse.Query(tokens);
userQuery.equalTo("myId",12); //sample
userQuery.matchesKeyInQuery("myId","myId", teamQuery);
userQuery.find({
success: function(results) {
// results has the list of users with a hometown team with a winning record
}
});
for the second query, you should have relation between two collections . and you can use matchesQuery method.

Meteor insert record using form values

First of all, I'm a complete JS novice. I'm experimenting with Meteor.My objective is to to build a simple form that inserts records into a table. I've set up variables to grab values from each input, and I've placed those variables into an insert method. When I click the button, it recognizes the click, but doesn't pull any values from the inputs. I'm sure I'm missing something simple here, I just can't figure out what it is.
Here's the JS:
var Leads = new Meteor.Collection("Leads");
if (Meteor.is_client) {
Template.Leads.LeadsArr = function(){
return Leads.find();
};
Template.AddLeads.events = {
"click input.submit" : function () {
var name = document.getElementById('input#name').value();
var email = document.getElementById('#email').value();
var type = document.getElementById('#type').value();
var date = document.getElementById('#date').value();
var message = document.getElementById('#message').value();
Leads.insert({leadName : name, leadEmail : email, leadType : type, leadDate : date, leadComment : message});
}
};
} // end is_client
document.getElementById expect the id, not the selector. Also, value is a property of an input, not a function. So your input queries should be like this.
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
var type = document.getElementById('type').value;
var date = document.getElementById('date').value;
var message = document.getElementById('message').value;

Categories

Resources