Please explain what is wrong as I have problems writing methods, and correct the code if you can.
Error: Compile Error: Variable does not exist: a at line 11 column 16
trigger tokenGenerator on Certification__c (before insert) {
static string randomString(){
for(Certification__c c: Trigger.new){
final String chars = 'BCD';
String a = '';
while (a.length() < 1) {
Integer idx = Math.mod(Math.abs(Crypto.getRandomInteger()), chars.length());
a += chars.substring(idx, idx+1);
}
}
return a;
}
Integer i;
if(i<100){
while(c.Name.contains(a)){
randomString();
i++;
}
c.Name = a;
}
else
c.Name = 'You ran out of TOKENS';
}
This code should generate a "UNIQUE" string every time it is triggered. The randomString method (the method itself shows couple of errors) generates a random string and should return it as 'a'.
The 'IF' statement should check if 'a' already exists in the table, if so generate a new string and if not assign that generated string to the 'c.Name' field.
Also when the given set of CHAR values expire(after all possible random number outcomes or 100 tries) the code should output 'You ran out of TOKENS'.
POSSIBLE STRINGS = {B,C,D} = 3 values according to my code, which I know how to increase, but I just want my 'TOKEN' to be unique 100% of the time.
i
is uninitialized, and it's not clear why you're calling 100 times - it won't check uniqueness. There's no need to use awhile()
loop to generate one random character.