I have a content type that in one of their fields need a value that is unique and auto-increment. There are several obvious solutions:

  • Use the node id that is unique and auto-increment.
  • The Serial module.

The problem with these solutions is that they use the MySQL auto-increments.

Drupal, by default, auto-increments the node ID (nid) and other IDs by one digit for each piece of content you create. You can see this if you visit your site by the node ID path:


However, sites that use database replication as a backup strategy (is my case) often will have non-sequential ids, meaning that you could see nids jump by two or more digits.


The MySQL auto_increment_increment variable determines how many digits to jump for each successive auto_increment value.

And then I have this problem:

How I can do to have a field with unique and auto-increments values?

  • Depends on place where you want your incrementation to be executed. You can use both hooks and rules variants but with rules you need to execute custom code to get max value of your field and for example increment it before/after assignment Aug 29, 2015 at 1:46

1 Answer 1


You can achieve it yourself in your custom form submit, lets suppose your field name is myfield ( machine name will be field_myfield and it is text) and your content type is news ( change them with your data) first in form alter you can hide it ( it you don't want user see it ) Get idea from my code

function yourmodule_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'news_node_form'){
          // if we are in adding new node hide that field and add custom submit handler

function _my_autoinrement_submit_handler($form, &$form_state) {
// search for the last value 
$query= db_select("field_data_field_myfield","mf") ->fields("mf")
 ->condition('bundle', 'news','=')
    ->condition('status', 1)
    ->orderBy('field_myfield_value', 'DESC')
     $result = $query->execute()->fetchAll();
         //get last value entered before this
        $lastValue= current($result)->field_myfield_value;
     // increment last value ( biggest one )
     $lastValue ++;
   //set it in node

  • thank you for the answer, but in your code, when multiples node are created at same time, the field get values repeated, because the query is execute at same time and sometime get the same value.
    – rpayanm
    Aug 31, 2015 at 12:57
  • @rpayanm yes this have this bug, but you notice that you think the same time means exactly the same time .If you found better solution please write down here to I learn it
    – Yuseferi
    Aug 31, 2015 at 13:58
  • I think that the solution is with Queue. Is usefully this tutorial.
    – rpayanm
    Aug 31, 2015 at 17:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.