5JavaScript API Code Samples

Getting Started with the Code Samples

To use the sample code in this appendix:

  1. Log in to Oracle CRM On Demand with an administrator role that includes the privilege: Upload Client Side Extensions and Manage Custom HTML Head Tag.

  2. Navigate to Admin, Application Customization, Custom HTML Head Tag.

  3. In the Custom HTML Head Tags Detail page, add the sample code.

For more information about getting started, see Getting Started with the JavaScript API and in particular see Privileges Required and Managing HTML Head Additions.

For each of the code samples, the entry point for running the custom code is either a call to the onReady() method, which is associated with the ready event, or the onLoad() method, which is associated with the onload event. The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content (for example, images) has also been loaded.

Note: When including JavaScript code within HTML, remember to include the code within <script> tags.

Code Sample 1 for Creating a Custom Button for Validation

The following sample code creates a custom button labeled Validate on the Opportunity Detail page. When the button is clicked, a validate function is called to validate the values of the Primary Revenue Amount and Next Step fields. The sample code also hides the Add button on the Contact related information applet.

// entry point for running custom code
oraclecrmod.onReady(function()

{

	// when on the Opportunity Detail page
	if(oraclecrmod.ctx.object == "Opportunity" && oraclecrmod.ctx.isDetailPage())

	{

		// define validate function
		function validate()

		{
			var revenue = oraclecrmod.getField("Primary Revenue Amount").getValue();
			var nextstep = oraclecrmod.getField("Next Step").getValue();
			// validate custom business logic goes here based on field values retrieved

		}


		// get the title bar
		titleBar = oraclecrmod.getTitleBar("OpportunityFormTB");
		// create the new Validate button
		button = oraclecrmod.createButton({id:"ValidateButton", text:"Validate", 
		parent:titleBar});
		// associate the validate function with the button click event
		button.on("click", validate);
		// get the Add button and hide it
		oraclecrmod.getButton("BTN_TB_ContactRoleChildList_ContactRoleNewNav").hide();

	}
});

Code Sample 2 for Creating a Custom Button for Validation

The following sample code creates a custom button labeled Validate on the Opportunity Detail page. When the button is clicked, a validate function is called to validate the values of the Primary Revenue Amount field. The sample code also hides the Add button on the Contact related information applet.

// entry point for running custom code
oraclecrmod.onReady(function()
{

		// OPPORTUNITY VALIDATE EXAMPLE //
		// when on the Opportunity Detail page
		if(oraclecrmod.ctx.object == "Opportunity" && oraclecrmod.ctx.isDetailPage())
		{

				// define validate function
				function validate()
				{

					var revenue = oraclecrmod.getField("Primary Revenue Amount").getValue();
					// convert to currency string to number
					var number = Number(revenue.replace(/[^0-9\.]+/g, ""));
					// validate custom business logic goes here based on field values retrieved
					if (number > 0) {

						var alertStr = "Recommendation is to fill in the field(s):\n";
						alertStr += "Next Step\n\n";
						alertStr += "Based on the rule(s):\n";
						alertStr += "Revenue is greater than 0\n\n";
						alertStr += "For this record:\n";
						alertStr += "Revenue is: " + revenue;
						alert(alertStr); 

					}
				}

				// get the title bar
				titleBar = oraclecrmod.getTitleBar("OpportunityFormTB");
				// create the new Validate button
				button = oraclecrmod.createButton({
					id:"ValidateButton", 
					text:"Validate", 
					parent:titleBar

				});
				// associate the validate function with the button click event
				button.on("click", validate);
				// get the Add button and hide it
				oraclecrmod.getButton("BTN_TB_ContactRoleChildList_ContactRoleNewNav").hide();
		}

});

Code Sample for a Custom Button That Creates a Record

The following code sample illustrates the use of the createRecord() method to create an Account record with three fields, Location, Type, and Description, when a button created with the createButton() method and labeled Test Create is clicked.

oraclecrmod.onReady(
	function()
	{
			if(oraclecrmod.ctx.isObject("Account") && oraclecrmod.ctx.isDetailPage())
			{
				var callback = function(request,response)
				{
	  				var data = "Response Data: ";
					var status = response.status;
					var error = "Error message: "
					if (status == "OK")
					{
						error += status;
					}
					else
					{
						error += response.errors;
					}
					var dataObj = response.data;
					if (dataObj != null)
					{
						data += "Id = " + response.getRowId() + ", Mod Id = " + response.getModId();
					}
					else
					{
						data += "Data is Null";
					}
					alert(data + "\n" + status + "\n" + error);
				};
				var createRecord = function()
				{
					oraclecrmod.dataSvc.createRecord("Account", {Name : "Account Name Create123",Location : "Location Test", Type : "Customer", Description "Description Test"}, "", callback);
				};
				var tb = oraclecrmod.getTitleBar("AccountFormTB");
				var bt = oraclecrmod.createButton({id:"TestCreateBtn",text:"Test 
				Create",parent:tb});

				bt.on("click",createRecord);

			}

	}

);

Code Sample for a Custom Button That Creates a Child Record

This following code sample creates a custom button labeled Create Task on the Opportunity Detail page. When the button is clicked, the REST API is used to create a child Activity record. In the createTask() function, you must replace <PodURL> with the URL for your pod. The Restful Services Integration privilege is required to send REST requests.

function createHttpRequest (httpmethod)

{

	var xmlhttpRequest = null;
	xmlhttpRequest = new XMLHttpRequest();
	if (typeof xmlhttpRequest.overrideMimeType != 'undefined')

	{

		xmlhttpRequest.overrideMimeType('application/json');
	}

	return xmlhttpRequest;

}


	oraclecrmod.onReady(function()
	{
		// when on the Opportunity Detail page
		if(oraclecrmod.ctx.object == "Opportunity" && oraclecrmod.ctx.isDetailPage())
		{

			function createTask()
			{

				var id = oraclecrmod.getField("Id").getValue();
				var insertPayload = "{\"Activities\":[ \
				{\
					\"Activity\": \"Appointment\", \
					\"Subject\": \"Opp Auto Appointment\", \
					\"Type\": \"Other\", \
					\"Location\": \"Markham\", \
					\"OpportunityId\":\"" + id + "\" \
				}\
				]}"


				//Calls REST API to create Task
				var url = "<PodURL>/OnDemand/user/Rest/026/Activities";
				var req = createHttpRequest ("POST");
				req.open('POST', url, false);
				req.setRequestHeader("Content-Type","application/
				vnd.oracle.adf.resource+json");
				req.send(insertPayload);
				alert(req.responseText);
				//success
				if (req.readyState == 4 && req.status == 201)
				{

					alert("success");

				}
		}
		// get the title bar
		titleBar = oraclecrmod.getTitleBar("OpportunityFormTB");
		// create the new button
		button = oraclecrmod.createButton({id:"CreateTaskButton", text:"Create Task",parent:titleBar});
		// associate the createTask function with the button click event button.on("click", createTask);

		}

	}

);

Code Sample for a Custom Button That Updates a Record

The following code sample illustrates the use of the updateRecord() method to update an Account record when a button created with the createButton() method and labeled Test Update is clicked.

oraclecrmod.onReady(
	function()

	{

		if(oraclecrmod.ctx.isObject("Account") && oraclecrmod.ctx.isDetailPage())
		{

			var callback = function(request,response)

			{

				var data = "Response Data: ";
				var status = response.status;
				var error = "Error message: "
				if (status == "OK")

				{

					error += status;

				}

				else

				{

					error += response.errors;

				}

				var dataObj = response.data;
				if (dataObj != null)

				{

					data += "Id = " + response.getRowId() + ", Mod Id = " + response.getModId();

				}
				
				else
				{

					data += "Data is Null";

				}
				alert(data + "\n" + status + "\n" + error);

			};
			var updateRecord = function()
			{

				oraclecrmod.dataSvc.updateRecord("Account", {Name : "Account Name Update123"}, "AUDA-1HSXSB", callback);
			};
			var tb = oraclecrmod.getTitleBar("AccountFormTB");

			var bt = oraclecrmod.createButton({id:"TestUpdateBtn",text:"Test Update",parent:tb});


			bt.on("click",updateRecord);

		}

	}

);

Code Sample for a Custom Button That Gets a Shipping Address to Pass to an External Site

The following code creates a custom button labeled Map Shipping Address on the Account Detail page. When the button is clicked, the shipping address is passed to an external URL, in this case, the URL for Google Maps.

// example: create a map button 
// entry point for running custom code
oraclecrmod.onReady(function()
{

		// when on the Account  Detail page
		if(oraclecrmod.ctx.object == "Account" && oraclecrmod.ctx.isDetailPage())
		{

			// define map function
			function map()
			{

				var wholeAddress = "";
				if (oraclecrmod.getField("Ship To Street Address") != null)
				wholeAddress += oraclecrmod.getField("Ship To Street Address").getValue() + " ";
				if (oraclecrmod.getField("Ship Street Address 2") != null)
				wholeAddress += oraclecrmod.getField("Ship To Street Address 2").getValue() + " ";
				if (oraclecrmod.getField("Ship Street Address 3") != null)
				wholeAddress += oraclecrmod.getField("Ship To Street Address 3").getValue() + " ";
				if (oraclecrmod.getField("Ship To County") != null)
				wholeAddress += oraclecrmod.getField("Ship To County").getValue() + " ";
				if (oraclecrmod.getField("Ship To Postal Code") != null)
				wholeAddress += oraclecrmod.getField("Ship To Postal Code").getValue() + " ";
				if (oraclecrmod.getField("Ship To Country") != null)
				wholeAddress += oraclecrmod.getField("Ship To Country").getValue() + " ";
				window.open("http://maps.google.com?q=" + encodeURIComponent(wholeAddress));

			}

        
			// get the title bar
			titleBar = oraclecrmod.getTitleBar("AccountFormTB");
			// create the new map button
			button = oraclecrmod.createButton({id:"mapButton", text:"Map Shipping Address", 
			parent:titleBar});
			// associate the map function with the button click event
			button.on("click", map);


			}
});

Code Sample for a Custom Button That Creates a Task

The following sample code creates a custom button labeled Assign Next Step Task on the Opportunity Detail page. When the button is clicked, a function is called to open the Task Open page with appropriate values. The task can then be saved and used to follow up on the next step for the opportunity.

// entry point for running custom code
oraclecrmod.onReady(function()
{

		// when on the Opportunity Detail page
		if (oraclecrmod.ctx.object == "Opportunity" && oraclecrmod.ctx.isDetailPage()) {
			// define createTask function
			function createTask() {
				var Id = oraclecrmod.getField("Id").getValue();
				var oppName = oraclecrmod.getField("Name").getValue();
				var nextstep = oraclecrmod.getField("Next Step").getValue();
				var desc = "Please follow up on the next step for this opportunity: " + 	nextstep;
				var subject = "Follow up on next step for " + oppName;
				var date1 = new Date();
				date1.setDate(date1.getDate() + 2);
				var dd = date1.getDate();
				var mm = date1.getMonth()+1; // month starts at 0 e.g. Jan = 0
				var y = date1.getFullYear();
				var date1Formatted = mm + '/' + dd + '/' + y;

				window.open("/OnDemand/user/
				TaskNew?OMRET0=OpportunityDetail%3fOpptyDetailForm.Id%3d" + Id + "&OMCR0=" + Id + 
				"&OCTYPE=&OMTGT=TaskEditForm&OMTHD=ActivityNewNav&OMCBO=Opportunity&TaskEdit
				Form.Due Date=" + encodeURIComponent(date1Formatted) + 
				"&TaskEditForm.Comment=" + encodeURIComponent(desc) + 
				"&TaskEditForm.Description=" + encodeURIComponent(subject), "_self");

		}	//createTask


			// get the title bar
			titleBar = oraclecrmod.getTitleBar("OpportunityFormTB");



			// create the new TASK button
			button = oraclecrmod.createButton({
				id: "createTaskButton",
				text: "Assign Next Step Task",
				parent: titleBar
			});


			// associate the createTask function with the button click event
			button.on("click", createTask);

		}
});

Code Sample for Hiding a Button

The following sample code hides the copy button on the Opportunity Detail page.

oraclecrmod.onReady(function()
{
		// when on the Contact Detail page
		if(oraclecrmod.ctx.object == "Opportunity" && oraclecrmod.ctx.isDetailPage())
		{
			// get the Copy button
			button = oraclecrmod.getButton("BTN_TB_OpportunityForm_OpportunityPreCopyNav");


			// hide the button
			button.hide();

		}
});

Code Sample for Changing the Behavior of a Save Button

The following code customizes the Save button on the Account Edit page so that the code changes the owner of the record:

oraclecrmod.onReady(

function(){

if(oraclecrmod.ctx.isObject("Account") && oraclecrmod.ctx.isEditPage()){

		var btnSave = oraclecrmod.getButton("BTN_TB_AccountEditForm_Save");

		if(btnSave != null){

			btnSave.offAll("click").on("click",function(){

				//set on screen value api to set the value.

				oraclecrmod.getField('Owner Alias').setValue("User1");

				btnSave.invokeDefault("click");
				});

			}

		}

});

Code Sample for a Read Operation on an Account Record

The following sample code is for a read operation to get details of an account and display them in the Description field on the Contact Edit page. A call is made to the readRecord() method to get the values for the Type and Location fields of the associated account.

// entry point for running custom code - only before the page loads
oraclecrmod.onLoad(function () {
	// CONTACT EXAMPLE //
	var contactCallback = function (request, response) {
		if (response.status == "OK") {
			var type = response.getFieldValue("Type");
			var location = response.getFieldValue("Location");
			//update the description field with account record info
			oraclecrmod.getField('Comment').setValue("This contact is created by the 
			account with type " + type + " and located at " + location);
		}
	}

	// when on the Contact new page
	if (oraclecrmod.ctx.object == "Contact" && oraclecrmod.ctx.isNewPage()) {
		//get the Account Id
		var acctId = oraclecrmod.getField("Account Id").getValue();
		if (acctId != null) {
			oraclecrmod.dataSvc.readRecord("Account", "Location,Type", {
 			  searchType: "rowId",
    				"rowId": acctId
			}, contactCallback);
		}
	}
});

Code Sample for Color Coding of Fields and Rows

The following code sets colors on pages as follows:

  • On the Opportunity Detail or Edit page, the colors of the label and value for the Primary Revenue Win Probability field are set, depending on the percentage value entered in the field.

  • On the Opportunity List page, the colors for the Primary Revenue Win Probability field are set, depending on the percentage value entered in the field, and rows where the Priority field has the value High are colored yellow.

  • On the Contact related item list of the Opportunity page, the color of the Role field is set, if the value of the field is Decision Maker.

  • On any page where there is a Name field, the field label background color is set to black, the field label text color to red, the field value background color to red, and the field value text color to black.

//color function for coloring the Opp detail/edit page
function colorOppty()

{

	//on the Opportunity detail/edit page, change the color for the Probability field depending on the percentage entered

	var percent= oraclecrmod.getField("Primary Revenue Win Probability");
	colorPercent(percent);

}
//color function for coloring the Opp List
function colorOpptyList(row)
{

	var percent= row.getField("Primary Revenue Win Probability");
	var priority = row.getField("Priority");
	colorPercent(percent);
	if (priority != null)
	{

			//set the row to Yellow in the list if the priority is High
			if (priority.getValue()=="High")
			{

				row.setColor({rowBgColor:"yellow"});
			} else {
					row.setColor({rowBgColor:""}); //this clears previous set color and will display based on theme color

			}
		}
}
//common color function to color the Probability field in the same way in the list page as it is colored on the detail/edit page
function colorPercent(percent)
{
	var myred = "#e71832";
	var myblue = "rgb(66,97,156)";
	var myyellow= "rgb(255,215,181)";
	if (percent != null)
	{

		if(percent.getValue()> 50)

		{

			percent.setColor({"labelBgColor":myred,"labelTextColor":myblue,"valueBgColor":myblue,"valueTextColor":myred});

		}
		else { 

			percent.setColor({"labelBgColor":"","labelTextColor":"","valueBgColor":"","valueTextColor":""}); //this clears previous set color and will display based on theme color
		}
	} 
} 
//color function for coloring the Opp's Contact Child List
function colorOpptyContactChildList(row)

{

		var role = row.getField("Role");
		if (role != null)
		{
				//set the row to Cyan in the list if the contact's role is Decision maker
				//change text of role to Red as well
				if (role.getValue()=="Decision Maker")
				{

					row.setColor({rowBgColor:"cyan"});
					role.setColor({valueTextColor:"Red"});
				}
				else {
					row.setColor({rowBgColor:""}); //this clears previous set color and will display based on theme color

					role.setColor({valueTextColor:""}); //this clears previous set color and will display based on theme color

			}

		}

}
// entry point for running custom code
oraclecrmod.onReady(function()
{   
			//if Name field exists on the form, then set the field label background to Black, field label text to Red, value background to red and value text to black

			//for example, this applies to Account Name on Account detail/edit page and Opportunity Name on Opportunity detail/edit page

			var name =  oraclecrmod.getField("Name");

			if (name != null) name.setColor({"labelBgColor": "Black","labelTextColor":"#ff0000","valueBgColor": "#ff0000","valueTextColor":"Black"});

			//get the form on the page for Opportunity
			if(oraclecrmod.ctx.object == "Opportunity")
			{

				//for the opportunity list page
				if (oraclecrmod.ctx.isListPage())
				{

					var oppList = oraclecrmod.getList();
					if(oppList != null)
					{
						oppList.on("display", colorOpptyList);
					}
				} else {
				//for detail/edit pages, etc
					if (oraclecrmod.getForm() != null)
				{

					oraclecrmod.getForm().on("display", colorOppty); //set the custom function to run on display of the form

				}
				var contactList = oraclecrmod.getList("ContactRoleChildList");
				if(contactList != null) {
					contactList.on("display", colorOpptyContactChildList); }
				}
		}
});