Saturday, August 22, 2009

Unique Numbers for Records

Creating unique numbers is something we are often asked to do. There are a number of ways of accomplishing this, from creating a separate entity that autonumbers when a workflow is activated, incrementing your number by 1, to combining several fields, to this, which is easy and creates a date/time based number when you create the record. This one uses just a snippit of code in your OnLoad event - the only thing you have to change is the field into which the number is to be entered.

In my example, we are creating commission records. The unique number is going into a field called Commission ID. The system name for the field is ptc_commissionid. This will create a new number only if the Commission ID field is empty.

Here's your unique num generator:

//Unique Num for Commission ID
var oCommissionID = crmForm.all.ptc_commissionid;

if (oCommissionID.DataValue == null)
{
oCommissionID.DataValue = (new Date().getYear().toString()).substr(2,2) + (new Date().getMonth() + 1).toString() + new Date().getDate().toString() + (new Date().getTime().toString()).substr(6,4);
}

Other letters or codes can be added to signify the entity or other information, if you wish. This pulls the last two digits of the year, the month, the day of the month, and a portion of the time in milliseconds, so duplication is very unlikely.

1 comment: