Hey all,

I've been trying to use this module to create a node title with a random unique 6-digit number as an identifier for one of my node types (e.g. "Posting 836712").

It is easy to generate a random number, but I was unsure of how to ensure that the number is unique. Below is the code that I used to solve the problem, in case anyone else out there is facing a similar challenge.

  //Pick a random six digit number
  $randNum = rand(100000, 999999);

  //Get the count of other node titles that include this number
  $unique = db_result(db_query("SELECT COUNT(*) FROM {node} n WHERE n.title LIKE '%%%s%%'", $randNum));

  //If there ARE other nodes with this number in the title, select another number.  Repeat until we have a unique number.
  while ($unique > 0) {
    $randNum = rand(100000, 999999);
    $unique = db_result(db_query("SELECT COUNT(*) FROM {node} n WHERE n.title LIKE '%%%s%%'", $randNum));
  }

  //Output the title, including our unique number
  return 'ID #' . $randNum;

Remember to check the "Evaluate PHP in pattern" box as well!

Cheers,
Bryce

Comments

danzsmith’s picture

The only issue with this is that it seems to generate a new random number and new title every time you edit and save the node...

Granted, that is of course when you use the "Automatically generate the title and hide the title field" setting. If you switch to the "Automatically generate the title if the title field is left empty" this behavior goes away on edit but the title field is exposed to the user, which is undesirable in my case.

It would be nice somehow to have this functionality no regenerate new titles on editing the node AND also be able to hide the title field.

Do we think that is possible?

Thanks for this contribution BTW...

brandy.brown’s picture

Issue summary: View changes

You can use this in conjunction with the Serial Field module. You'll have to also use the token module to call that field as the replacement. https://drupal.org/project/serial