Auto generate incrementing integer
BWPanda - September 8, 2008 - 01:35
| Project: | Automatic Nodetitles |
| Version: | 5.x-1.1 |
| Component: | Miscellaneous |
| Category: | support request |
| Priority: | normal |
| Assigned: | Unassigned |
| Status: | active |
Jump to:
Description
I'd like nodes of a certain type to have their title field as an incrementing integer (e.g. 001, 002, 003, etc.)
I've tried using the [nid] token, but it increments even when another type of node is created, giving this sort of effect: 001, 003, 004, etc.
Anyone know an easy way of doing this?

#1
(Subscribe)
I just created a forum topic about that topic, before I read this issue: http://drupal.org/node/305328
#2
I found one way to do it...
I put the following code in the pattern for my auto nodetitle (set to PHP obviously):
<?php
$sql = "SELECT count(nid) AS number FROM {node} WHERE type = 'node_type'";
$result = db_query($sql);
$data = db_fetch_array($result);
$id = sprintf("%03d", $data['number'] + 1);
return $id;
?>
It counts the number of nodes of a given type (node_type) and adds some leading 0's to it.
The only problem is that it doesn't count deleted nodes (i.e. if you have 15 nodes (the last of which has a title of '015') and you delete a node, the next one you create will be given the title of '015'...) This may or may not be ideal for certain situations, in my case I'll just stop users from deleting nodes.
Hope this helps!
EDIT: Oops, changed the sprintf function to increment the number so if there are 15 existing nodes, the new one will be titled '016' :)
#3
Just came across another problem...
When you edit an existing node, the PHP is run again and the number changes.
Any ideas how to stop this happening?
#4
could this be the answer?
Actually, seems that this is the answer...
#5
I actually just ended up using the Workflow-NG module to run the PHP code whenever a node of a particular type was created. This stops it running after being edited.
#6
BWPanda: My problem is that nodes on my site are often deleted.... and as you mentioned in comment #2 this will be a problem...
Thank you!
#7
<?php$sql = "SELECT max(nid) AS num FROM {node}";
$result = db_query($sql);
$data = db_fetch_array($result);
$id = sprintf("%03d", $data["num"] + 1);
return $id;
?>
#8
@potss - that's an interesting one...!