Can this module be used to generate random numbers? For example, I wanted a field to contain a number from 1-20 calculated when the entity is saved.

Thanks.

Comments

draenen’s picture

Title: Random numbers » Add function to compute random numbers
Category: Support request » Feature request

The module does not yet support random numbers but I think it would be a good feature to add.

jigish.addweb’s picture

Try the Computed Field module, which allows you to create fields whose values are defined by PHP snippets. For a random number, you might use something like this in your field's "Computed Code" configuration:

$node_field[0]['value'] = rand();

Note that rand() also accepts min and max arguments, in the form of rand(min, max).

Also be sure to enable the "Store using the database settings below" setting with a data type of "int" and a reasonable data length based on the expected range of values for rand(). This will ensure that the field isn't recomputed every time the node is displayed.

NOTES: The above method stores a new random value each time the user updates/resaves the node. If you'd like the field to generate and store a random number once and only once for each node (at the node's initial save), try something like this instead:

if (!$node_field[0]['value']) {
  $node_field[0]['value'] = rand();
}

This will only set a value for the field if one doesn't already exist.

Let me know if any query regarding this.

Thanks!