Generate A Random Number, Apply a Check Digit
Last updated on
30 April 2025
I needed to create a field that would contain a unique serial number for certain node types. Using Computed Field, this was pretty easy. But, the twist was that the serial number would need to contain a check digit. To avoid ever re-generating the serial number and overwriting an existing value, I check to see if the field is not-empty.
if (!empty($node_field[0]['value'])) { // The PIN has already been generated, do nothing
return $node_field[0]['value'];
}
else { // Time to create a PIN. Generate a random number, calculate a check digit via modulus-9, and append the check digit to the generated number
$pin = rand(1000000,2000000);
$numArray = explode(" ", $pin);
$arraySum = array_sum($numArray);
$remainder = $arraySum % 9;
$difference = 9 - $remainder;
$node_field[0]['value'] = $pin.$difference;
}
Help improve this page
Page status: Not set
You can:
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion