JavaScript Function to Pull related object fields - javascript

I am using the following query to try to pull fields off of a User lookup on the Account. There is a field on the Account called Dedicated_Rep__c which is a user lookup. I am building my button off the opportunity, and I want to be able to pull the Opportunity's Account's Dedicated Rep's First Name, Last Name, and Email. Here's my code:
function getDedicatedAccountRep (oppId) {
var result = sforce.connection.query("select Account.Id, Account.Dedicated_CS_Rep__r.FirstName from Opportunity where Id = '" + oppId + "' ");
if(!result || result['size'] != 1) {
return null;
}
var DedRepRole = result.getArray('records')[0];
return DedRepRole.Account;
}
var dedicatedRep = getDedicatedAccountRep('{!Opportunity.Id}');
I am getting an error:
Cannot read property 'Dedicated_CS_Rep__c' of undefined
I am referencing the code later in the button and I am instantiating it by putting: dedicatedRep.Dedicated_CS_Rep__r.FirstName

Start with something like that (I prefer the Google Chrome's javascript console, you can open it with Ctrl+Shift+J; but feel free to use Firefox + Firebug or IE's developer tools...)
{!requireScript("/soap/ajax/29.0/connection.js")}
var result = sforce.connection.query("SELECT Account.Dedicated_CS_Rep__r.FirstName FROM Opportunity WHERE Id = '{!Opportunity.Id}'");
console.log(result);
debugger;
This will let you inspect the query result and play with the results. I think your problem is that the full expression can look like this:
result.records.Account.Dedicated_CS_Rep__r.FirstName
A lot can go wrong here. result should be OK and records should be always 1 row since we run it for one Opportunity (let's ignore crazy scenarios where somebody deleted the Opp between you navigating to the page and clicking the button... But still:
the Account can be blank (out of the box it's perfectly valid to have private Opportunities; maybe your organisation has marked the field as required).
And similarly in theory it's valid to have Account without the user.
So - you have 2 chances to hit null pointer exception:
Therefore properly protected code would have this orgy of null / undefined checks:
{!requireScript("/soap/ajax/29.0/connection.js")}
var result = sforce.connection.query("SELECT Account.Dedicated_CS_Rep__r.FirstName FROM Opportunity WHERE Id = '{!Opportunity.Id}'");
console.log(result);
if(result != null
&& result.records != null
&& result.records.Account != null
&& result.records.Account.Dedicated_CS_Rep__r != null){
alert(result.records.Account.Dedicated_CS_Rep__r);
// return result.records.Account.Dedicated_CS_Rep__r;
} else {
alert('Nope');
// return null;
}

Related

PDF.js Setting a field value?

I hope you're all doing well. So I've been working with PDF.js by Mozilla for a while now. We're using it to display PDF forms to be filled out on a mobile app. Everything works great, I'm just trying to implement a feature where you can cache the users entries so that they can resume from where they left off. For a few reasons I can't just download the PDF to save it and then load it back up when they wat to resume.
Essentially I want to store all the user entries and the Field ID for each of them, which I've already gotten working, and then when the user wants to resume I want it to load the empty PDF, and then automatically re-populate all the fields with the cached entries.
I know I could set the individual text fields, but when I do that it doesn't apply to the annotationStorage so when I parse the form, those fields are read as blank.
I've tried the following lines of code in an attempt to set a field value with the id "5R"
PDFViewerApplication.pdfDocument.annotationStorage.setValue('5R', "Shirboogle");
PDFViewerApplication.pdfDocument.annotationStorage.getAll()['5R'].value = "Shirboogle";
var objs = await PDFViewerApplication.pdfDocument.getFieldObjects();
objs['Address 1 Text Box'][0].value = "Shirboogle";
// and
objs['Address 1 Text Box'][0].defaultValue = "Shirboogle";
// This will actually set the value of the text field, but when I look for it in annotationStorage OR
// getFieldObjects() the value is still unchanged.
document.getElementById('pdfjs_internal_id_5R').value = 'Shapoopsies';
along with many other attempts. I've looked all over and nothing seems to be available, so if you have any ideas please let me know!
In case anyone is having trouble with this, here is the solution I came up with. It seems to work great for my use case but may not be sufficient for every case. I figured I'd at least share what I got to work.
It basically sets everything manually. There are still some UI elements I need to make an if statement for to set, but anyways. Here's my code. Good luck :)
function getFieldValue(id) {
return PDFViewerApplication.pdfDocument.annotationStorage.getAll()[id].value;
}
async function getFieldObjById(id) {
var objs = await PDFViewerApplication.pdfDocument.getFieldObjects();
for(var i=0; i<Object.values(objs).length; i++) {
if(Object.values(objs)[i][0].id == id) {
return Object.values(objs)[i][0];
}
}
}
async function setFieldValue(id, val) {
var fElementId = "pdfjs_internal_id_" + id;
var fObject = await getFieldObjById(id);
var objType = fObject.type;
// Depending on the element type we set the value accordingly.
if(objType == 'text') {
document.getElementById(fElementId).value = val;
PDFViewerApplication.pdfDocument.annotationStorage.setValue(id, {value: val});
}
else if(objType == 'checkbox') {
document.getElementById(fElementId).checked = val;
PDFViewerApplication.pdfDocument.annotationStorage.setValue(id, {value: val});
}
else if(objType == 'combobox') {
document.getElementById(fElementId).selectedIndex = val;
var sLabel = document.getElementById(fElementId).options[document.getElementById(fElementId).selectedIndex].label;
PDFViewerApplication.pdfDocument.annotationStorage.setValue(id, {value: sLabel});
}
}

Verify if there is an empty input text/email/date with Javascript?

I'm learning how to program so bear with me. I pretty much need to verify if there are empty spaces in a form that needs to be filled out, I'm using javascript. I did the following but for some reason even if I fill out all the spaces it still tells me that there are empty spaces.
(This his how the HMTML for each id looks like)
<label for="txtNombre">Name</label>
<input type="text" id="txtName" placeholder="Name">
let inputName = document.querySelector('#txtName').value;
let inputLastName = document.querySelector('#txtLastName').value;
let inputPassword = document.querySelector('#txtPassword').value;
let inputConfirm = document.querySelector('#txtConfirm').value;
let inputDate = document.querySelector('#dDate').value;
function validateForm(){
let bError = false;
if(inputPassword === '' || inputConfirm === '' || inputName ==='' || inputLastName === '' || inputDate === ''){
bError = true;
showMessage(bError);
}else if (inputPassword === inputConfirm) {
inputPassword.classList.remove('borderError');
showMessage(bError);
} else{
inputPassword.classList.add('borderError');
bError = true;
showMessage2(bError);
}
}
function showMessage(pbError){
divMessage.innerHTML = '';
divMessage.classList.remove('error');
divMessage.classList.remove('correct');
let spanMessage = document.createElement('span');
let nodeMessage;
if(pbError === true){
divMessage.classList.add('error');
nodeMessage = document.createTextNode('Missing fields to be filled out');
}else{
divMessage.classList.add('correcto');
nodeMessage = document.createTextNode('Data saved');
}
spanMessage.appendChild(nodeMessage);
divMessage.appendChild(spanMessage);
divMessage.classList.remove('invisible');
}
Since your questions doesn't hold any of your html code, and since Im unsure if you javascript is the entire script, or if there is anything defined outside the scope of your functions, my answer is limited to the information you have provided.
First off, since you are a new developer. You should first of, learn
how to use the developer tools of the browser you are using (most
browsers have them). There should be a console there, which will log
all the errors that occurs in your javascript. This is the most
efficient way to debug your code.
As someone have commented on your question here, the most likely error, is that the variables you are trying validate as blank or not, are undefined variables. Thus, they will never match ""
You should refer to the value of the input fields before you check them.
Lets say you have a input field:
<input name="test" type="text" id="testinput" />
Then you define the variable that refers to the value of this input, and check its value:
var testInput = document.getElementById('testinput').value
if( testInput === "" ) //Do something
Note, there are several methods to refer to a DOM-element in javascript, getElementById is just one of them. You should do some research, and choose the solution that fits you best
assuming that you are storing the input value in those varialiables like inputPassword for example:
const inputPassword = document.getElementById('myInput').value
Your code should work as far as I can tell from what you have posted.
Hope it helps

transfer date into input field from one asp form into another using session state

I need to transfer date from one asp form to another based on some checks.
In the source page I do the check and send as following:
if (txtFinalized.Text == "" && rblPhysicalrecords.SelectedValue=="1" && ddlResponsibility.SelectedIndex == 5)
{
//String s = Request.QueryString["finlalisationDate"] = txtFinalized.Text;
Session["finlalisationDate"] = txtFinalized.Text;
}
Then I try to read the value in the target form but so far I can't get the resut inserted into the input field as I need.
txtFinalised.Text = (string)(Session["finlalisationDate"]);
Do I need to write a method in javascript to fetch the result and insert it to the field and if yes how do I do that?
Your condition block has a flaw, it says txtFinalized must be empty to set a value to your session variable.
For learning and and understand session you could write your code like this...
//remove txtFinalized from condition
if (rblPhysicalrecords.SelectedValue=="1" && ddlResponsibility.SelectedIndex == 5)
{
//check if textFinalized NOT is null or empty
if (!String.IsNullOrEmpty)
{
Session["finlalisationDate"] = txtFinalized.Text;
}
//if textFinalized is empty set session to a value just to see some text
else
{
Session["finlalisationDate"] = "n/a";
}
}
Now when you load your second form you will always see something in your textFinalized textbox and from what you see you know if the user made some input in the first form.
You can modify your condition block like below
if (!String.IsNullOrEmpty(txtFinalized.Text) && rblPhysicalrecords.SelectedValue=="1" && ddlResponsibility.SelectedIndex == 5)
{
//String s = Request.QueryString["finlalisationDate"] = txtFinalized.Text;
Session["finlalisationDate"] = txtFinalized.Text;
}

Check if nested object is declared and has a value without so many conditional checks

I have a JSON object which I get from a server. The key which I get the value from looks something like this:
var myJson = data.body.region.store.customer.name;
I am trying to get the name key here, but sometimes the JSON (which comes from a service I have no control over) will have some empty fields, like for instance name might not be defined so the object will actually look like this: data.body.region.store.customer. Sometimes too customer, or store, or region might not be defined (If the data doesn't exist the service doesn't return a null or empty string for the value).
So if I need the name what I am doing is this:
if(data.body.region.store.customer.name){
//Do something with the name
}
But say even store isn't defined, it will not get the value for name(which I would expect to be undefined since it doesn't exist) and the program crashes. So what I am doing now is checking every part of the JSON before I get the value with AND operands:
if(data && data.body && data.body.region && data.body.region.store && data.body.region.store.customer && data.body.region.store.customer.name){
//Do something with the name value then
}
This works, because it checks sequentially, so it first checks does data exist and if it does it checks next if data.body exists and so on. This is a lot of conditions to check every time, especially since I use the service a lot for many other things and they need their own conditions too. So to just check if the name exists I need to execute 6 conditions which of course doesn't seem very good performance wise (and overall coding wise). I was wondering if there is a simpler way to do this?
var myJson = null;
try {
myJson = data.body.region.store.customer.name;
}
catch(err) {
//display error message
}
You can try following
function test(obj, prop) {
var parts = prop.split('.');
for(var i = 0, l = parts.length; i < l; i++) {
var part = parts[i];
if(obj !== null && typeof obj === "object" && part in obj) {
obj = obj[part];
}
else {
return false;
}
}
return true;
}
test(myJson, 'data.body.region.store.customer.name');

Receiving "undefined" errors when trying to access object details

I'm very much a beginner when it comes to javascript, so I hope that you will bear with me.
I have an html file that contains a table with three values for reporting on a variety of system statuses - name, status, and notes. I am pulling the contents of the table into a variable, and scanning it for tags that point to an offline or partially online system. If found, the system name, status, and any notes concerning its status are stored into an object array (at least, I think it is an object array - I'm new at this).
Here's where I am having trouble. While I am looping through the table looking for a matching value, I am able to display an alert with the appropriate information as it is assigned to the object (example SmartPay, Offline, Not taking credit cards). Once I am out of the loop, I am unable to reference any data that I have stored. Here's the object constructor and function that I am working with:
function status(name, status, notes) {
this.name = name;
this.status = status;
this.notes = notes;
}
function parseStatus() {
var tagMatch = document.getElementsByTagName("td");
var problemStatus = new Array();
var j = 0;
for (i = 0; i < tagMatch.length; i++) {
if (tagMatch[i].textContent == "Offline" ||
tagMatch[i].textContent == "Partially Online") {
problemStatus[j] = new status(tagMatch[i-1].textContent,
tagMatch[i].textContent, tagMatch[i+1].textContent);
alert("OFFLINE: " + problemStatus[j]['name'] + ", " +
problemStatus[j]['status'] + ", " + problemStatus[j]['notes']);
j++;
}
}
}
The alert at the end of the for loop displays everything correctly. If I add this after the end bracket for the loop
alert(problemStatus[0]['name']);
I get "Cannot read property 'name' of undefined"
I do not understand where I am going wrong. Can someone please point me in the right direction?
Edited to include the link to JSFiddle

Categories

Resources