I have created a button to escalate a case. I am trying to change the record type, the "Owner" and append "Case Escalated" to the "Notes" field.
Code:
{!REQUIRESCRIPT("/soap/ajax/27.0/connection.js")}
var objCase = new sforce.SObject('Case');
objCase.Id = '{!Case.Id}';
objCase.Owner__c = 'Global Salesforce Team';
objCase.RecordTypeId = '012C00000007l5WIAQ';
objCase.Notes__c += 'Case Escalated';
var result = sforce.connection.update([objCase]);
if(result[0].success=='true'){
alert('The Case was Updated Successfully');
location.reload(true);
} else if(result[0].success=='true'){
alert('There was an issue updating the case');
}
However this wipes the "Notes" field and adds in "undefinedCase Escalated" instead of appending the string "Case Escalated" to the end of whatever is in there.
I am new to javascript, please be nice :)
i saw the code and the problem seems to be that you are creating a new instance of the Case to update, so there is nothing on the field Notes, and once you insert the record it overwrites with the only text there, 'Case Escalated', to get this to work you have to do a query to look for the value that was before on the field and then append the value to the notes__c field.
{!REQUIRESCRIPT("/soap/ajax/27.0/connection.js")}
var result = sforce.connection.query("select Id, Owner__c, RecordTypeId, Notes__c from Case WHERE Id='{!Case.Id}' LIMIT 1");
var records = result.getArray('records');
var objCase = records[0];
objCase.Owner__c = 'Global Salesforce Team';
objCase.RecordTypeId = '012C00000007l5WIAQ';
objCase.Notes__c += 'Case Escalated';
var result = sforce.connection.update([objCase]);
if(result[0].success=='true'){
alert('The Case was Updated Successfully');
location.reload(true);
} else if(result[0].success=='true'){
alert('There was an issue updating the case');
}
The link to the developer guide with an example is at http://www.salesforce.com/us/developer/docs/ajax/apex_ajax.pdf
Havent tested it and there is some error handling to be done in my code, but it should work.
Related
I have a Tag in tag manager that feeds me back the data of fields that have been showing as invalid when a user tries to submit a form but its missing or has invalid fields.
This is done using the following code:
// Get user Agent
var Uagent = navigator.userAgent;
// Validation Errors Check
document.getElementById("btnSubmit").onclick = function() {
errorLoop();
}
function errorLoop() {
var runner = document.getElementsByClassName("invalid"),
formEmail = document.getElementById('email').value,
dataL = [];
dataLayer.push({'formEmail' : formEmail});
if (runner) {
for (var i = 0; i < runner.length; i++) {
var errName = runner[i].getAttribute("name"),
errId = runner[i]
.getAttribute("id");
dataL.push("Field: " + errName + " - ID: " + errId);
} //End for
dataL.toString();
var vadout = dataL + " Device: " + Uagent;
console.log(dataL);
dataLayer.push({
'formEmail' : formEmail,
'validationError': vadout,
'event' : 'errorpush'
});
} //End if
} //End errorLoop
So whats basically happening here is on a submit we are checking the form to see if any of the fields have the class invalid & if it does then it add's the name & Id of the fields to an array then prints then prints the array into a data layer.
The tag itself is triggered using a custom event called errorpush.
The issue is that this works only about 80% of the time we still get alot of people get validation errors but the validation errors don't seem to make it to the datalayer and back to google analytics.
I'm considering adding a settimeout delay to the datalayer push which I will go away and try but wanted to see if anyone knows of anything right off the bat which could be causing this problem.
Your runner is declared as empty array if there are no elements with class name "invalid". But your if statement is only checking for declaration thus:
if(runner){
}
will always be true but there are no "invalid" elements. Consequently dataL.push("Field: " + errName + " - ID: " + errId);will never execute in your for loop but dataLayer.push will, and so you will get errorpush event without any errors.
To solve this, I would suggest to rewrite your if statement:
if(runner.length > 0){
}
I hope this solves your problem.
{!REQUIRESCRIPT("/soap/ajax/33.0/connection.js")}
/*Getting the Running User Details*/
var result =
sforce.connection.query(
"SELECT Advisor__c " +
"FROM User " +
"WHERE Id = '{!$User.Id}'"
);
/*Grab the Records returned by executing the above SOQL Query*/
var userDetails = result.getArray("records")[0];
/*Initializing the Contact record for Update*/
var contactToUpdate = new sforce.SObject("Contact");
contactToUpdate.Id = "{!Contact.Id}";
/*If the Running User is an "Advisor" then set the
Contact With and associated fields*/
if(userDetails.Advisor__c === true){
contactToUpdate.Contact_With__c = "{!$User.Id}";
contactToUpdate.Last_Advisor_Touch__c = new Date();
}
/*If the Running User isn't an "Advisor" then set the
Contact With 2 and associated fields*/
else{
contactToUpdate.Contact_With_2__c = "{!$User.Id}";
contactToUpdate.Last_Non_Advisor_Touch__c = new Date();
}
var result = sforce.connection.update([contactToUpdate]);
if(result[0].success === true){
location.reload();
}
else{
alert(result[0].errors.message);
}
I added a custom check box field to our user profiles titled "Advisor" The code is suppose to distinguish which field to update based on if a user has this box checked or not. If yes update this field, If not update that field. Instead though it's returning a 'Unexpected Token ILLEGAL. Not sure why.
Seems like you have a special hidden character in following line
contactToUpdate.Last_Advisor_Touch__c = new Da te();
in word Date
If you just rewrite it it should work.
Specifically you have the infamous ZERO WIDTH SPACE between Da and te probably comes from this. To eliminate such things you can use this tool or this one
I am trying to add create an editable table in HTML. So, I need to add rows, when user clicks on a button. Here is the code I am using.
//remove all old rows.
while (summaryTableElement.firstChild) {
summaryTableElement.removeChild(summaryTableElement.firstChild);
}
//add a new text area in the summary field.
summaryTableElement.innerHTML = "<textarea id='summaryTextBox' value='' onblur='saveSummary()'> </textarea> ";
This code works fine on Chrome and Mozilla. But, IE doesn't allow editing innerHTML. This HTML will be displayed inside a VB form, so I have "browser" and "webbrowser" controls available. Both of those controls use IE engine, so this code does not work there.
I have tried using firstchild.innerHTML instead so that I am not editing table row directly, and even that gave me same error.
I tried using WebKitBrowser. But, that causes an exception on load. Apparently that control uses some old method, and the method is changed. So, that control is out of question too.
Now, I am confused as to how to solve this problem?
Edit:
I found the issue with WebKitBrowser. It was specific to x86, while my project was targeting both x64 and x86. Switching it to x86 for both, worked. Although, webkit browser do not take return key values. So, I have a new problem. Pressing enter does not create a new line in table cell, and instead passes the event to vb form.
Edit:
Okay, so I tried working further with WebKitBrowser. But, that control gives me accessviolatedexception. So, I am thinking about going back to using the default browser control, for now.
As for default control, I checked further. Apparently, code works fine in IE9 and above. But, vb.net control uses some weird JS engine. So, I am receiving error only in vb control.
Here is the complete code for reference:
var summaryChanges = "";
var isSummaryClickable = true;
//creates a textbox for editing purpose and include the original summary data.
function modifySummary(id) {
var summaryTableElement; //to get the table cells so that we can access the value
var originalSummary = ""; //to hold the original summary while we create a text box
var loopCounter = 0;
if (isSummaryClickable == true) {
isSummaryClickable = false; //saves event spilling when clicked on the newly created textbox
//get the summary table id saved.
summaryTableElement = document.getElementById (id).childNodes.item(0);
//add existing data to a string to save it for later.
for (loopCounter = 0; loopCounter < summaryTableElement.childNodes.length; loopCounter++) {
originalSummary = originalSummary + summaryTableElement.childNodes.item(loopCounter).childNodes.item(0).innerHTML + "\n";
}
//remove all old rows.
while (summaryTableElement.firstChild) {
summaryTableElement.removeChild(summaryTableElement.firstChild);
}
//add a new text area in the summary field.
summaryTableElement.innerHTML = "<tr><td><textarea id='summaryTextBox' value='' onblur='saveSummary()'> </textarea></td></tr> ";
//set the width of the textbox to allow easy modification
document.getElementById("summaryTextBox").style.width = '600px';
//add original summary text to the text area and set focus
document.getElementById("summaryTextBox").value = originalSummary;
document.getElementById("summaryTextBox").focus();
}
}
// saves the updated summary data back to HTML
function saveSummary()
{
var newHTML = "";
var changesSummary;
var changesSubString = new Array();
var index = 0;
var elementToUpdate;
//get the summary table id saved.
elementToUpdate = document.getElementById("SummaryData"); //.childNodes.item(0);
//get changes from the textbox
changesSummary = document.getElementById("summaryTextBox").value;
//generate string array for separate lines from summaryChanges
changesSubString = changesSummary.split("\n");
//generate new HTML string for the summary fields
//alert(changesSubString.length);
for (index = 0; index < changesSubString.length; index++) {
newHTML = newHTML + "<tr><td class='Text' style='padding-left: 4px;padding-bottom: 4px;' id='SummaryLine" + index + "'</td>" + changesSubString[index] + "</tr>"
}
//update the HTML to the element
elementToUpdate.innerHTML = newHTML;
//allow clicking on summary table
isSummaryClickable = true;
}
function doNothing(id) {
//empty function for future use
return;
}
//this function is called from vb.net script to read the js variable.
//do not change the function definition (name or parameters or return type)
//any change will cause error in vb.net script
function jsInvokedFunction() {
var updatedHTML; // to be used by vb.net invoked function to get updated body
var testVariable = "test";
updatedHTML = document.body.innerHTML.toString();
return updatedHTML.toString();
}
I receive an error at the start of the line summaryTableElement.innerHTML = " ";
It is possible I am missing some other error, but I couldn't find any.
This is my sample script i write.
Task :
-To create a pop up message to show user if they haven't register as a member on system.
-User must have name inside the note view "Staff information by name"
-if user have name inside the view, it will write a message to a reviewer, to inform review what they request for.
-if user don't have name in "staff information by name" view, it will pop up a message to told user what to do.
// address book
var db:NotesDatabase = session.getDatabase("websvr/pcs", "names", false);
var vw2:NotesView = db.getView("($VIMPeople)");
var dc2:NotesDocumentCollection = vw2.getAllDocumentsByKey(document1.getItemValue("Name"),true);
var doc2:NotesDocument=dc2.getFirstDocument();
while (doc2!=null){
sname=doc2.getItemValueString('LastName')
doc2=dc2.getNextDocument();
}
// end of address book
//current database
var vw:NotesView = database.getView("Staff Information By Name");
var doc:NotesDocument = vw.getDocumentByKey(sname, true);
//check whether have setting on reviewer for current user else will be hard code to specific person
if (doc!=null)
{
revname=doc.getItemValueString("Reviewer")
rev=doc.getItemValueString("ReviewerEmail");
//set Email
var maildoc:NotesDocument=database.createDocument();
var body=maildoc.createMIMEEntity();
var stream=session.createStream();
var content="Dear "+revname+",<br></br>"+
"Please click <a href='http://"+applicationScope.hostname+"/"+(applicationScope.dbfilepath).replace(/(\\)/g, "/")+"/"+
"RequisitionForm.xsp?databaseName="+applicationScope.serverCN+"!!"+
applicationScope.dbfilepath+"&documentId="+
document1.getDocument().getUniversalID()+
"&action=editDocument'>here</a> to view it if you are in a web browser (eg: Internet Explorer, Mozilla Firefox, Google Chrome etc.)"+
"<br /><br /><b>OR</b><br /><br />"+
"<a href='"+document1.getDocument().getNotesURL()+"'>here</a> if you are in the Notes Client. Thank you.";
stream.writeText(content);
body.setContentFromText(stream, "text/html; charset=iso-8859-1", 0);
maildoc.replaceItemValue('Subject', 'Kindly review this '+document1.getItemValueString('Item')+' request by '+document1.getItemValueString('Name')+" on "+I18n.toString(#Today(), 'dd/MM/yyyy'));
maildoc.send(rev);
document1.replaceItemValue("TotalCost",document1.getValue("Cost")*document1.getValue("Qty"));
document1.replaceItemValue("Status","Pending");
document1.save();
context.redirectToPage("/MyRequisition.xsp");
}
else
{
a = 'alert("You do not have access right, please contact admin to register!")' ;
view.postScript(a);
break;
}
The sample script that work on other page :
a = 'alert("The applicant details must be unique!")' ;
b = 'alert("Applicant Details inserted!")' ;
var vw:NotesView = database.getView("Staff information by Name");
var doc:NotesDocument = vw.getDocumentByKey(getComponent("Name").getValue(), true);
if (doc!=null){
view.postScript(a);
break;
}
else
{
var newDoc = database.createDocument();
newDoc.appendItemValue("Form", "Staff Form");
newDoc.appendItemValue("Name", getComponent("Name").getValue());
newDoc.appendItemValue("Designation", getComponent("Designation").getValue());
newDoc.appendItemValue("Department", getComponent("Department").getValue());
newDoc.appendItemValue("Reviewer", getComponent("Reviewer").getValue());
newDoc.appendItemValue("Email", getComponent("Email").getValue());
newDoc.appendItemValue("ReviewerEmail", getComponent("ReviewerEmail").getValue());
newDoc.save();
getComponent("Name").setValue("");
getComponent("Designation").setValue("");
getComponent("Department").setValue("");
getComponent("Reviewer").setValue("");
getComponent("Email").setValue("");
getComponent("ReviewerEmail").setValue("");
view.postScript(b);
}
postScript() works only with partial refresh. If your code runs in event handler in full refresh mode, your postScript statement will have no effect.
Alternate solution is to use Output script (xp:scriptBlock) component with something like this:
var message = "#{requestScope.message}";
if (message) {
alert(message);
}
In your SSJS just set your message:
requestScope.message = condition ? "True!" : "False!";
http://publib.boulder.ibm.com/infocenter/domhelp/v8r0/index.jsp?topic=%2Fcom.ibm.designer.domino.ui.doc%2Fwpd_controls_cref_scriptblock.html
You can user facesContext and postscript to call JavaScript function on server side.
facesContext.getViewRoot().postScript("alert('"+documentName.getItemValueString("FieldName"));
So I have an .aspx page. In this grid I'm adding a bunch of controls. The first control however is an ExtObject, not one of our preset VB.NET controls. When I go to access the value on the backend for this field with this code:
form.AndOr.getValue()
It doesn't work. I really have no idea what is wrong. Basically, the radio button value isn't saving when I save the rest of the stuff. So I tried to add code to do it. It was just defaulted to 'And' each time. Below is a snippet of code from the actual asp.net grid. Any ideas?
With .Item(2)
.Ref = "../Payee2"
.LabelWidth = 90
With .AddFieldSet("Payee 2")
.AddControl(New Forms.Control("", "../PayeeId")).Hidden = True
.AddControl(New Forms.Control("", "../AddressId")).Hidden = True
.AddExtObject("{xtype:'radiogroup', ref:'../AndOr', defaults:{name:'rdo-payee2'}, width:120, items:[{boxLabel:'And', checked:true, inputValue:'and'},{boxLabel:'Or', inputValue:'or'}]}")
Dim ddlPayee2 As New Controls.ComboBox("", "../PayeePreInfo2", "Payee")
With ddlPayee2
.ForceSelection = True
.TypeAhead = False
.EmptyText = "Select Payee Details"
.ValueField = "AddressId"
.XTemplate = "applicantTemplate"
.ClientStore = "applicantAddressStore"
.AddListener(Akcelerant.Framework.WebControls.Controls.EventType.Select, "function(){prefillPayee('PAYEE2');}")
End With
.AddControl(ddlPayee2)
With .AddControl(New Forms.Control("", "../FirstName", "First Name", ""))
.Validate.MaxLength = 50
.ReadOnly = EditControl.IsFieldReadOnly(10483, True)
End With
With .AddControl(New Forms.Control("", "../LastName", "Last Name", ""))
.Validate.MaxLength = 50
.ReadOnly = EditControl.IsFieldReadOnly(10484, True)
End With
The error it throws is this:
Stack overflow at line: 16736
edit:
reverted some changes back and everything saves EXCEPT that value into the DB.
go to add this line to the javascript save function
if (form.AndOr.getValue() == 'and') {
payeeRec.set('IsPayee2RequiredToSign', 1);
} else {
payeeRec.set('IsPayee2RequiredToSign', 0);
}
and i get this error:
form.AndOr is not defined
Does the Ext ref: mean something different than my controls and how I access them?
Added a ref to the item of checkWin.
Then the ref to the radio value became
checkWin.Payee2.AndOr.getValue()
With that it can recognize the control on the form.