Calculated field using JavaScript API

I have created a “Date of Birth” Custom Field (Type: Date) on the Contact object, and my requirement was to create a field that would display the Age of the Contact, based on the “Date of Birth” field.

For that I used the Connect Desktop Integration (JavaScript API), and did the following:

  • Step 1: Create a Custom Field (Type: Integer) in the Contact object with the name “Age”, and add the field to the Contact workspace.

img1

  • Step 2: Create an HTML file with code to calculate the Age and set the “Age” field.

<html>
<head>
<script type=“text/javascript”>
function SetAge()
{
var dobInt = window.external.Contact.GetCustomFieldByName(“c$date_of_birth”);
if (dobInt == –1)
{
var textna = “N/A”;
window.external.Contact.SetCustomFieldByName(“c$age”, textna);
return;
}
var dob = new Date(dobInt * 1000);
var now = new Date();
var yearAge = now.getFullYear() – dob.getFullYear();
var monthNow = now.getMonth() + 1;
var monthDob = dob.getMonth() + 1;
if (monthNow < monthDob || (monthNow == monthDob && now.getDate() < dob.getDate()))
yearAge–;
window.external.Contact.SetCustomFieldByName(“c$age”, yearAge);
}
function ondataupdated(obj)
{
SetAge();
}
</script>
</head>
<body onload=SetAge()>
</body>
</html>

  • Step 3: Upload the HTML file to a server via FTP and take the URL.
  • Step 4: Add a new tab to the Contact Workspace and drag and drop a browser control into the tab

img2

  • Step 5: Select the browser control, go to the Design tab > Options section, and put the URL of the HTML file into the URL field.

img3

  • Step 6: Select the new tab, go to the Design tab > Behavior section, click the Hidden button and make the tab hidden “On New” and “On Open.

img4

  • Step 7: Select the browser control, go to the Design tab > Options section, and un-check the Delay Page Load check box.

img5

Now, whenever you open a contact that has “Date of Birth” populated, the script will calculate the Age and set the “Age” Custom Field with the right value.

img6

You might also want to make the “Age” field read only so that its value is only set by the script and not by the user.

Important Note: The date fields only allow to go back to 1970, which in this case of Date of Birth is a bit limited.

Thank you to Jens Lundell (Oracle RightNow Workflow Development Manager) for his help on this requirement and to Mark Kehoe (Independent Oracle RightNow Consultant) for raising the date limitation issue.