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
Joanna Knott 6Joanna Knott 6 

Alpha-numeric auto generated ID

Is there a way to create an alpha-numeric auto generated ID consisting of random letters and numbers?
Gaurav NirwalGaurav Nirwal
function generateID()
{
    $capital_letters = range("A", "Z");
    $lowcase_letters = range("a", "z");
    $numbers         = range(0, 9);

    $all = array_merge($capital_letters, $lowcase_letters, $numbers);
    $count = count($all);    
    $id    = "";

    for($i = 0; $i < 10; $i++)
    {
        $key = rand(0, $count);
        $id .= $all[$key];
    }

    if(!uniqueId($id))
    {
        return generateID();
    }
    return $id;
}

Gaurav NirwalGaurav Nirwal
composite (alphanumeric) primary key and auto increment

public function random_id_gen($length)
    {
        //the characters you want in your id
        $characters = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
        $max = strlen($characters) - 1;
        $string = '';

        for ($i = 0; $i < $length; $i++) {
            $string .= $characters[mt_rand(0, $max)];
        }

        return $string;
    }


Joanna Knott 6Joanna Knott 6
I tried this in a formula field on the account object but it was giviing me errors. 
Pratik_MPratik_M
Hi Joanna,

You can refer to this post: http://salesforce.stackexchange.com/questions/43823/how-do-i-generate-a-random-string

public static String generateRandomString(Integer len) {
    final String chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
    String randStr = '';
    while (randStr.length() < len) {
       Integer idx = Math.mod(Math.abs(Crypto.getRandomInteger()), 62);
       randStr += chars.substring(idx, idx+1);
    }
    return randStr;
}

Thanks,
Pratik