The Zurich release has arrived! Interested in new features and functionalities? Click here for more

Create a unique value for field

Lucy10
Tera Contributor

I need some assistance on creating a unique value for a fields on the the cmdb table.

I have using a client script on submit to create the alpahnumeric value but I need some help with checking if the value is unique and if not create another value.

My script;

var tagID = g_form.getValue('u_tag');

var text = "";

  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  for (var i = 0; i < 5; i++)

      text += possible.charAt(Math.floor(Math.random() * possible.length));

  g_form.setValue(tagID, text);

 

}

Thanks,

Lucy

1 ACCEPTED SOLUTION

Thanks for the update Lucy.



Your code is close... I suspect you go that from the top search of Stack Overflow.



I would put it in a before business rule that only runs on Insert (not update). Check Advanced and the script will look more like this. Granted - I haven't tested this yet.



(function executeRule(current, previous /*null when async*/) {



var text = "";


var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";


var unique = false;


var tableName = current.getTableName();



while (!unique) {


  for (var i = 0; i < 5; i++)


      text += possible.charAt(Math.floor(Math.random() * possible.length));



  // Check to see if any other record has this ID in the u_tag field (change field names below if it's not u_tag)


  var rec = new GlideRecord(tableName);


  if (!rec.get('u_tag', text)) {


        unique = true;


}


}



current.u_tag = text;



})(current, previous);


View solution in original post

8 REPLIES 8

Gaurav Bajaj
Kilo Sage

HI Lucy,



I would suggest you to create random number based on current time just like sys id in ServiceNow are created.


This will make sure that it's always unique and there won't be any recurrence of any sort.



Thanks


Gaurav


The requirements it has to be 5 character   and alphanumeric.   Is there a business rule for sy id creating?


sergiu_panaite
ServiceNow Employee
ServiceNow Employee

If you really want to be sure 100% that you don't insert duplicate values, create a unique index on that field. Any INSERT for duplicate values will be rejected. You can only create a unique index if you do not have any duplicate values now, otherwise index creation will also fail.


Chuck Tomasi
Tera Patron

Hi Lucy,



It sounds like you've zeroed in on a solution before we understand the requirements. I know you're looking for a unique ID...



Does it have to be a client script? In other words, does it have to be visible to the user before submitting the value?



Is this for new records only? Meaning, do you need to show a unique value on an empty form?