You can generate a random number between 0 and 1000 with below method using Math class as below: Integer IntrandomNumber = Integer.valueof((Math.random() * 1000));
I am a beginner and I know nothing about how to write code in apex but I have one field name as random which should automatically generate one number populate that field how can i accomplish it.
If you want that on record creation, you can refer writing below trigger:
//Assuming Obj__c is the Object's API Name and random__c is the field's name
Trigger ObjTrigger on Obj__c (before insert){
for(Obj__c obj : Trigger.New){
Integer IntrandomNumber = Integer.valueof((Math.random() * 1000)); //generates a random number from 0 to 1000
obj.random__c = IntrandomNumber;
IntrandomNumber += 1;
}
}
Hi Danish, I wrote code under triggers it worked fine but Its giving an error as the datatype for the random field is text. so can I convert the output to string/ text so as to avoid decimal values.
You can generate a random number between 0 and 1000 with below method using Math class as below:
Integer IntrandomNumber = Integer.valueof((Math.random() * 1000));
If you want to generate a random string, plz refer the post: https://thesalesforcedev.blogspot.com/2019/12/generate-random-string-in-apex-public.html
How can i populate new custom field with the random number generated by this script
I wrote code under triggers it worked fine but Its giving an error as the datatype for the random field is text. so can I convert the output to string/ text so as to avoid decimal values.
You can change the line #7 as below:
obj.random__c = String.valueOf(IntrandomNumber);