function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
AbAb 

generate a unique code everytime a record is stored by trigger

Hello,

How can i generate the a 10 digit random code everytime a record is created, by trigger

Thank you for suggestion
 
Best Answer chosen by Ab
Shivam Yadav 8Shivam Yadav 8
Hi Sandrine,

This Can be done by 2 ways-
1. With Apex and
2. WIth Formula field

If you want to do this by apex than here is the code -

First Solution(Apex Code) :

String hashString = '1000' + String.valueOf(Datetime.now().formatGMT('yyyy-MM-dd HH:mm:ss.SSS'));
Blob hash = Crypto.generateDigest('MD5',
Blob.valueOf(hashString));
String hexDigest = EncodingUtil.convertToHex(hash);
system.debug('##########' + hexDigest );

Second Solution(Formula) : 

LEFT(TEXT(
SQRT(
(VALUE(
(LEFT(RIGHT(TEXT( CreatedDate ),6),2))&
TEXT(DAY(DATEVALUE(CreatedDate)))&
TEXT(MONTH(DATEVALUE(CreatedDate)))&
TEXT(YEAR(DATEVALUE(CreatedDate)))&
(LEFT(RIGHT(text(CreatedDate),6),2))) )*10 ) ) ,3 ) &
LEFT(Your_FIeld, 3)

Thanks

All Answers

Shivam Yadav 8Shivam Yadav 8
Hi Sandrine,

This Can be done by 2 ways-
1. With Apex and
2. WIth Formula field

If you want to do this by apex than here is the code -

First Solution(Apex Code) :

String hashString = '1000' + String.valueOf(Datetime.now().formatGMT('yyyy-MM-dd HH:mm:ss.SSS'));
Blob hash = Crypto.generateDigest('MD5',
Blob.valueOf(hashString));
String hexDigest = EncodingUtil.convertToHex(hash);
system.debug('##########' + hexDigest );

Second Solution(Formula) : 

LEFT(TEXT(
SQRT(
(VALUE(
(LEFT(RIGHT(TEXT( CreatedDate ),6),2))&
TEXT(DAY(DATEVALUE(CreatedDate)))&
TEXT(MONTH(DATEVALUE(CreatedDate)))&
TEXT(YEAR(DATEVALUE(CreatedDate)))&
(LEFT(RIGHT(text(CreatedDate),6),2))) )*10 ) ) ,3 ) &
LEFT(Your_FIeld, 3)

Thanks
This was selected as the best answer
Khan AnasKhan Anas (Salesforce Developers) 
Hi,

Greetings to you!

Below is the sample code which I have tested in my org and it is working fine. Kindly modify the code as per your requirement.
trigger UniqueCodeGenerator on Account (before insert) {
    
    for(Account acc : trigger.new){
        Integer len = 10;
        Blob blobKey = crypto.generateAesKey(128);
        String key = EncodingUtil.convertToHex(blobKey);
        String pwd = key.substring(0,len);
        System.debug('************ '+pwd);
        acc.Unique_Code__c = pwd;
    }
}

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas