-3

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.

5
  • What’s the problem? Commented Oct 22, 2018 at 5:09
  • Error: Compile Error: Unexpected token 'private'. at line 3 column 9 Commented Oct 22, 2018 at 6:05
  • You can’t define a function inside of a for loop.... Commented Oct 22, 2018 at 6:14
  • I changed the code, now i get this error Error: Compile Error: Variable does not exist: a at line 11 column 16 Commented Oct 22, 2018 at 6:34
  • 1
    There are a lot of issues with this code. You can't define a function inside a trigger. 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 a while() loop to generate one random character.
    – David Reed
    Commented Oct 22, 2018 at 11:37

1 Answer 1

3

You're defining a inside a for loop and accesss it out of scope. Move the definition before the loop (then it's in the same scope as the return).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .