I need to set the node title to the nid. I assume I need some php code to do this? Or is it not possible as the node will not have an nid until it is saved?
Thank you

Comments

hmm...similar thing happens with [author-name] on first registration:

cannot assign title because user name is not saved yet...any thought on this much apreciated!

thx

You're right (node-based) tokens are not available to use in autonodetitle when you create a new node, because, well, the node which they reference doesn't exist yet... however, you can reference the values which have been submitted in the form itself though.

To get the author's name, edit your content type settings for Automatic title generation to make sure that 'evaluate PHP in pattern' is checked, and then try this:

<?php
 
global $form_values;
 
$title = 'This is a new node written by '. $form_values['name'];
  return
$title;
?>

Status:Active» Fixed

As already said, It's not possible.

Status:Fixed» Closed (fixed)

Automatically closed -- issue fixed for two weeks with no activity.

download:
http://drupal.org/project/auto_nodetitle

set "Automatically generate the title if the title field is left empty" and in "Pattern for the title:" write:

<?php
$name
= db_prefix_tables('{node}_nid');
$id = db_result(db_query("SELECT id FROM {sequences} WHERE name = '%s'", $name)) + 1;
return
$id;
?>

this is great, i added some code to get a random number

<?php
$name
= db_prefix_tables('{node}_nid');
$random = (rand()%1025);
$id = db_result(db_query("SELECT id FROM {sequences} WHERE name = '%s'", $name)) + $random * 3;
srand(time());
return
$id;
?>

don't forget to check "Evaluate PHP in pattern"

The problem with adding a random number is that you are not guaranteed a unique number for your title.

You could retrieve an ID of 50, for example, and add the randomly generated number 2 - producing 52; then, the next time you create content of that type, you could retrieve an ID of 51 and if the random number generated is 1, you end up with 52 again! That's why adding 1 every time will work better (you will have a unique number).

I agree with you, but you can solve that with a bigger range of random numbers, if you generate a random number between 1 and 9, you will get the same numbers a lot, but if you generate a random number between 10,000 and 99,999, the possibility of getting the same number it's smaller (just math).

But that's not the biggest problem, after I submitted the last comment, I started to use a lot that code, and even when I only use the sequence query (without adding a random number), if I edit the node the Node Title changes because it's getting another value from the sequence table.

I have no idea of how to solve this.

Luis

I've used this successfully in the past for getting around the [nid] issue:

<?php
//wrap [nid] in quotes or else we'll get a parse error
$token = '[nid]';
if (!empty(
$token)) {
 
// this node is not new
 
return [author-uid] . '-' . [type] . '-' . $token;
}
else {
 
// this node is new
 
$nid = db_next_id('{node}_nid');
  return [
author-uid] . '-' . [type] . '-' . $nid;
}
?>

comment #5 will work but not when editing a node. If you edit an old node you will see that the node title is changed to the next sequential nid.

For the person commenting on #9, be careful if you use the function db_next_id() because this will increment the nid as well. You may not want this. And this will also not work if you edit an old node.

I have altered the code and found the following code to work and takes care of the case for editing old nodes as well:

<?php
$token_nid
= '[nid]';
$token_type = '[type]';
if (!empty(
$token_nid)) {
 
// this node is not new
 
return $token_type . ' - ' . $token_nid;
}
$name = db_prefix_tables('{node}_nid');
$id = db_result(db_query("SELECT id FROM {sequences} WHERE name = '%s'", $name)) + 1;
return
$token_type . ' - ' . $id;
?>

How would i do this if i wanted to use a taxonomy term which was only just chosen as the title for the node?

Hmm, not sure but I am guessing that the tax. term will be stored in some variable at the time you submit (maybe $node). But do you really want to do this in the first place? what would happen if two users created a node with the same taxonomy term? That would mean two nodes with the same title.

Also what happens if a user chooses more than 1 tax. term?

Yes, i do want to do this. Two users won't choose the same taxonomy term in this case. Only a few users will have the access to use this. It will be for "online instructors" to create a course title. They will not have any need to choose more than 1 tax term and i will set it so that this is not possible.

It works fine if the user saves the node and then goes into edit and saves again and i can live with this if need be, but if there is a way to get around this, it would make things much less complicated.

#9's solution worked for me, adding +1 to the node ID when this is a new one.

<?php
//Define your Prefix:
$prefix='My-[type]-';
//wrap [nid] in quotes or else we'll get a parse error
$token = '[nid]';
if (!empty(
$token)) {  // this node is not new:
 
return ("$prefix-$token");
}
else { 
// this node is new:
 
$nid = db_next_id('{node}_nid') +1;
  return (
"$prefix-$nid");
}
?>

If your using MySQL here's the code that Drupal 5 uses for db_next_id():

<?php
function db_next_id($name) {
 
$name = db_prefix_tables($name);
 
db_query('LOCK TABLES {sequences} WRITE');
 
$id = db_result(db_query("SELECT id FROM {sequences} WHERE name = '%s'", $name)) + 1;
 
db_query("REPLACE INTO {sequences} VALUES ('%s', %d)", $name, $id);
 
db_query('UNLOCK TABLES');
  return
$id;
}
?>

If your using postgreSQL, it does the same thing, but uses the postgreSQL function nextval() to calculate the sequence.

So long as you have an else statement following the check for the existence of nid, you can safely use db_next_id() and not have to worry about incrementing anything, because you will definitely be dealing with new node, and your essentially assigning the nid the same way Drupal does.

Same issue. I don't like the offered solutions; In a heavy duty website titles may not actually correspond to the nid. That is, if many requests are made at the same time, db_next_id could return the same id for multiple nodes, unless i am mistaken.

On creation of a new node the nid doesn't exist. So why not make the system automatically edit the node after it has been safed?

Just a thought.

Status:Closed (fixed)» Postponed (maintainer needs more info)

I am sorry to reopen this issue. I am however desperately in need of a solid solution here. As in my previous post, I am concerned that the offered solution may not provide the actual nid. In a heavy duty website with thousands of users, if many people are adding posts in the same time, I am concerned that #14 might provide the same number for multiple nodes. So I have a theoretical solution in mind, and i hope that someone could give me some thought on it.

When I think about using Token, I think about Pathauto. Using the nid in Pathauto seems to work fine. I think this is because pathauto writes the path to the database after the node has been saved, thus having no problem using the nid. As far as I can tell Automatic Nodetitles alters the Title of a node before saving the node, therefore making the use of nid for the creation of nodes impossible. This in my opinion is in conflict with what Automatic Nodetitles should be able to do, it's not really logical that it can use Token, but not nid, author and perhaps other Tokens. So I think the module should be changed to save the node title in a similar way that Pathauto does; just a simple "UPDATE" SQL after the node has been saved and all data is available from Token.

Any comments on this? Thanks.

Version:5.x-1.1» 6.x-1.0
Status:Postponed (maintainer needs more info)» Needs review

Hi again.
I hacked a possible solution. I don't know how to create a patch, so i am posting the code here. It is a nodeapi function, and it will only be called on creation of a new node. So basically a new node is saved 2 times. I put the code after auto_nodetitle_set_title, on line 74. Try it out and give me some feedback please!

/**
* Implementation of hook_nodeapi().
* Needed for newly saved nodes
*/
function auto_nodetitle_nodeapi(&$node, $op, $teaser, $page) {
// First check if this nodetype is auto_nodetitle enabled
$setting = auto_nodetitle_get_setting($node->type);
if ($setting == AUTO_NODETITLE_ENABLED || ($setting == AUTO_NODETITLE_OPTIONAL && empty($form_state['values']['title']))) {
switch ($op) {
// We only need to do this for new nodes. It will save the node again after creating the title
case 'insert':
$types = node_get_types();
$pattern = variable_get('ant_pattern_'. $node->type, '');
if (trim($pattern)) {
$node->changed = time();
$node->title = _auto_nodetitle_patternprocessor($pattern, $node);
}
else if ($node->nid) {
$node->title = t('@type @node-id', array('@type' => $types[$node->type]->name, '@node-id' => $node->nid));
}
else {
$node->title = t('@type', array('@type' => $types[$node->type]->name));
}
node_save($node);
break;
      default:
        break;
    }
  }
}

I revised my code a little bit. Now it will put the title in AFTER the node is being saved, regardless whether its new or updated. The code should go in auto_nodetitle.module around line 74. This should work for drupal 5, but this is untested. I am using drupal 6.4.

/**
* Implementation of hook_nodeapi().
* Needed for newly saved nodes
*/
function auto_nodetitle_nodeapi(&$node, $op, $teaser, $page) {
// First check if this nodetype is auto_nodetitle enabled
$setting = auto_nodetitle_get_setting($node->type);
if ($setting == AUTO_NODETITLE_ENABLED || ($setting == AUTO_NODETITLE_OPTIONAL && empty($form_state['values']['title']))) {
switch ($op) {
// Now works for insert and update. Title is stored in database with db_query instead of node_save
case 'insert':
case 'update':
$types = node_get_types();
$pattern = variable_get('ant_pattern_'. $node->type, '');
if (trim($pattern)) {
$node->changed = time();
$node->title = _auto_nodetitle_patternprocessor($pattern, $node);
}
else if ($node->nid) {
$node->title = t('@type @node-id', array('@type' => $types[$node->type]->name, '@node-id' => $node->nid));
}
else {
$node->title = t('@type', array('@type' => $types[$node->type]->name));
}
drupal_set_message($node->title . t(' has been generated. Node id is ') . $node->nid);
db_query("UPDATE {node} SET title = '%s' WHERE nid = %d", $node->title, $node->nid);
db_query("UPDATE {node_revisions} SET title = '%s' WHERE nid = %d AND vid = %d", $node->title, $node->nid, $node->vid);
break;
      default:
        break;
    }
  }
}

subscribing.

subscribing

this code seems to be working fine for me. no problems (yet). thank you for this.

for Drupal 5 works ok.

Status:Needs review» Needs work

This code won't get into the official module - so I change the status.

Does #2 work in six? I can't seem to get it working. I need to get the value of the publish_on field from the scheduler module into the title.

Tried

<?php
 
global $form_values;
  return
$form_values['publish_on'];
?>

without any luck?

Great job Dagomar, thank you very much

quick question, how would I modify the code on #19 to remove the nodetype in front of the nid to get a title resembling "1234" instead of "Story 1234"

Thank you

I would imagine this can be done with the pattern you select?

For instance, i wanted the title of the node to be the nid, so i just used [nid] as title. This can be done on
"/admin/content/types/yourcontenttype" and then 'Automatic title generation'. I chose "Automatically generate the title and hide the title field" and as pattern "[nid]", like a said. If u have problems just PM me.

Is everyone using #19 as a solution for this or has there been anything else available that we can use to get the [nid] as the Title during creation in D6?

Susbscribing

There's a lot of comments with code in this issue, most of them work. I know the logic way to do this would be just to add the token [nid] but that won't work without a patch, instead you have to use some php code, I usually use #14 without a problem.

There's a simple workaround using the Rules (or Workflow-ng) module

See http://drupal.org/node/360359#comment-1460918

If the patch in #19 works, what still needs work here? Not clear on why it can't be rolled into the module. I think dagomar's reasoning makes alot of sense.

takinola you are a legend... thanks for your solution. I agree with Aharown07 why hasn't this rolled into the module already?

I'll add that I've been using patch19 for a few days now in test environment and have not seen any problems. (I don't really want to install Rules since I have no other use for it and it looks a bit heavy... that and I can't seem to understand how to make it work :) )

subscribe

Version:6.x-1.0» 6.x-1.x-dev
Component:Miscellaneous» Code
Category:support» feature
Status:Needs work» Needs review

Updating issue.

Just create a rule. Similar to the suggested solution in http://drupal.org/node/360359#comment-1460918, I use the following in the custom PHP code option for actions on "add a node":

$node->title = $node->nid;

This does not require automatic nodetitles.

This is not working with the latest dev version, and I can't seem to get the code from #19 to work.

Is someone working on adding this to the module? Or could someone please tell me where to add the above mentioned code in either version? Thanks in advance.

#19 is still working fine for me. You put it in auto_nodetitle.module. I don't remember now if I just added the code or replaced what was there but in my file it starts around line 61 and ends around 94.
I think it basically replaces the whole hook_nodeapi implementation part.

No idea why it hasn't been rolled into the module or made avail as an admin option or something.

Thanks aharown07, I just replaced the hook_nodeapi part with the code, and it's working well.

Good... now we both know! :) (... and I thought I'd documented all my hacks so well)

Ok I applied #19. However if I set "Automatically generate the title if the title field is left empty" and enter or type a value or something in the Title field it ignores it and enters the content type an node id no. Or am I not understanding something? I thought it's supposed to use the entered value first?

Just used a simple workaround to create an automatic node title based on the nid

<?php
if ($node->title) {
echo
$node->title;
}
else {
$sql = "SELECT COUNT(*) FROM {node} WHERE type = 'contenttype' AND status = 1";
$total = db_result(db_query($sql))+1;
echo
$total;
}
?>

Version:6.x-1.x-dev» 6.x-1.1

ok, #42 - this good way, but title != global nid...
i'm not sure, but this code work for me:

<?php
$ts_row
= mysql_fetch_array(mysql_query(SHOW TABLE STATUS LIKE 'node'));
echo
$ts_row[‘Auto_increment’] ;
?>

(sorry my english)

one moment... if "Automatic title generation" set to "generate the title and hide the title field", code

if ($node->title) {
echo $node->title;
} else {...
return "ant", therefore this way true only for opened title field

for use "Automatically generate the title and hide the title field" I add node_load (maybe exist best way?):

<?php
$n
= node_load($node->nid);
if (
$n->title) {
   echo
$n->title;
} else {
  
$ts_row = mysql_fetch_array(mysql_query("SHOW TABLE STATUS LIKE 'node'"));
   echo
$ts_row['Auto_increment'] ;
}
?>

Status:Needs review» Active

Just setting status to "active" as there is no real patch here. But let's keep that issue open so that interested users can find it.

StatusFileSize
new1.88 KB

Rolled dagomar's change from comment #19 into a patch (patch is against version 1.1). That is attached. IMO, this should become part of the module.

Version:6.x-1.1» 6.x-1.2

#19 works with version 1.2 as well. I second @attheshow: this should become part of the module.

StatusFileSize
new1.94 KB

I'm not sure the patch in #46 is quite right - the path isn't correct. Attached patch should work for 1.1 and 1.2 (and possibly earlier).

I have an 'item ID' that is unique for each record and needs to be generated (auto-incremented) and used as the node title as well as a CCK field upon CCK form save, so I presume I can simply replace NID in patch #48 with any other DB variable I may be using, like 'item ID' in this case, and add some code to populate the CCK field at the same time, right?

Where can I find info on what code is needed to populate the CCK field? I'm not a developer but could probably hack my way through it if pointed in the right direction. I do have a copy of "Pro Drupal Development".

Is there anything else unique to using NID in the patch that I need to change?

I think it might be worth writing a module to generalize this feature for use not only with the NID and title field but other auto-increment fields and CCK fields in general, or just generalize the design of this module and rename it appropriately.

I applied the patch above and I still get the node title of 'ant'.

•ant has been generated. Node id is 3148
•Contacts ant has been created.

Is this a general issue for all the on save features like Author Name , Node creation year etc? If so shouldn't the documentation on Replacement patterns mention it? Or is that down to Token?

Also I was curious why there are no Node creation time replacement patterns? or is that Token too?

Found http://drupal.org/node/207768#comment-1329294 which appears to have a Token patch which might mean this patch wasn't needed?

Patch in #48 works for me. The patch needs some tweaks to match Drupal code style (spacing, doc formatting, else if should be elseif), and it should be rolled within the module dir (http://drupal.org/patch/create ).

Patch #48 work great, Thanks jim0203

I try the #30 and it work but geocode from a field don't work any more :(
I open an issue #574894: Geocode don't work with rules with triger "after the node is saved "

EDIT: work great with patch #48 Thanks!

Patch #48 works perfectly, I think it's the right solution! When it'll be ported to dev version?

Status:Active» Reviewed & tested by the community

I added the code from #19 into auto_nodetitle.module after row 75 and I immediately get a nasty php error:

Fatal error: Cannot redeclare auto_nodetitle_nodeapi() (previously declared in /home/xxx/domains/dannyjoris.be/public_html/yyy/sites/all/modules/auto_nodetitle/auto_nodetitle.module:64) in /home/xxx/domains/dannyjoris.be/public_html/yyy/sites/all/modules/auto_nodetitle/auto_nodetitle.module on line 109

I put the code into place before I uploaded and installed it.

--Edit: it works now. Putting the code after row 75 was for version 6.x-1.0. I had version 6.x-1.2 . Replacing the function auto_nodetitle_nodeapi() on row 64 will do the trick.

@fago
would this be accepted into the module if it would be written as an optional checkbox - "Run after content has been saved", hence exposing all node tokens and closing off any issues relating to this? what would be the performance issues related to checking that checkbox?

Status:Reviewed & tested by the community» Needs work

A check box is not realy cool they need a DB request...
But we can certainly improve performance because nid never change:

So we can use "insert" with the code of the patch and keep "presave" when the node already existe.

pseudo code:

<?php
case 'presave':
//nid is already set (node exist) OR we don't need the nid in title
if(!isset($node->nid) || "nid is not in the paterne so we don't need it"){
  
auto_nodetitle_set_title($node);
}
break;
case
'insert':
//we need the nid in title?
if("nid present in $paterne so we need it"){
 
///So we change title after insert....
}
?>

What do you think?

Has anyone seen this new module for CCK unique, atomic serial numbers?

The claim is it's accomplished in the same way that NIDs are.

http://drupal.org/project/serial

Hi guys, I am not sure if this will help some of you, but for us this is a working solution when we need the NID as part of title.

After trying some of the stuff for auto_nodetitle we decided to use rules like posted in #39 (http://drupal.org/node/360359#comment-1460918).

Create a rule "after saving new content", create condition "if type is one of yours with auto_nodetitle" and add an action "custom PHP code" with:

auto_nodetitle_operations_update(array($node->nid));

we are using node_autotitle-6.x-1.2+

Tom

my solution ...

<?php
$lastNodeID
= db_result(db_query("SELECT nid FROM {node} order by nid DESC limit 1 "));
echo
$lastNodeID."/".(float)microtime()*10000000;
// to start with serial based on the node id
$lastNodeID = db_result(db_query("SELECT nid FROM {node} order by nid DESC limit 1 ")) + 1;
echo
$lastNodeID;
?>

quick & fast .. hope this will help u!

Will the solution in 48 be committed?

I write in 61 that's the patch in 48 is good but not perfect because is always search nid in presave instead of check before if we have or not already a nid (this is the case if you save after edit).

use code #64 ...

StatusFileSize
new710 bytes

This is a very simple issue. Currently, Automatic Nodetitles hooks into the 'presave' operation, presumably so it can modify the title and not have to worry about saving the node (as this will subsequently done by core). Obviously, the problem with this is that the node has not been saved yet, and so we don't have access to things like NID, or in my case - the CCK Serial field.

The simple solution is to change the hook_nodeapi reference so that it triggers on the 'insert' operation rather than 'presave' AND THEN also re-saves the node. This change is only a few lines of code. To give everyone some perspective, this is how modules like Pathauto work. The only downside to this method is you are saving the node again, but this is really not resource intensive.

I've attached my patch below. I really think this should be strongly considered as a permanent addition to the module. Or, at the very least, add an administrative option that allows the selection of 'presave' or 'postsave' title generation.

StatusFileSize
new731 bytes

Updated patch from #68 -- forgot to include the 'update' operation in addition to 'insert'.

Status:Needs work» Needs review

StatusFileSize
new828 bytes

I just modified the patch #69 to explain my idea but it's perhaps totally wrong:
- on first insert use "insert" and resave the node
- on update use the "presave" so resave is not needed

watching this issue. i need nid in my titles.

applying patch at #71 I got:

File to patch: ./auto_nodetitle.module
patching file ./auto_nodetitle.module
patch: **** malformed patch at line 21:

this is against the official relase of module for 6, not dev.

Please use #69 for review, not #71.

@gagarine -- if you're going to post a patch, please be sure its code you've at least tested yourself first, rather than simply editing the .patch file and re-posting. Not only is your patch not applying, but your revision is incomplete. You are missing a 'break' after your 'insert' case.

While I agree that this would be another way to approach the fix, my preference would be to keep the code as simple as possible as in #71.

Status:Needs review» Needs work

The patch should probably unset $node->revision before doing the save, as this can cause revision numbers to get messed up with other modules which implement hook_nodeapi().

As this should only happen on insert, I would recommend re-rolling this patch to use the idea in #71, this will avoid other issues that might occur with saving the node twice when the revision flag is set.

subscribe

@ISPTraderChris Sorry for the bad patch but is to present a concept has explain in my post.

Anyway, I see some potential issue with the module Rules: If we save the node two times actions runs two times...

#75 good catch about revision...

Perhaps a more direct SQL query to change the node title after is saved instead of reuse node_save is better. Why do you think?

@Gagarine

I agree. After spending more time with this I see that my proposed patch, in addition to saving the node twice, also triggers another complete round of hook_nodeapi() calls - which is not ideal. My patch does not take into account the potential revision issue mentioned above, and it unnecessarily calls node_save() on both insert and update operations, when it really is only necessary on insert (presave is sufficient for existing nodes).

I think we may be able to simply call drupal_write_record('node', $node) on the insert operation to save the node title without hitting hook_nodeapi() but have not had a chance to test this out yet.

Patch #69 works but causes other problems. Looking for another solution

this is the way i used to solve the problem externally:

create a separate module which implement hook_nodeapi with code like this

function example_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  if ($op == 'insert') {
    unset($node->auto_nodetitle_applied);
    if (auto_nodetitle_is_needed($node)) {
      auto_nodetitle_set_title($node);
      db_query("UPDATE {node} SET title = '%s' WHERE nid = %d", $node->title, $node->nid);
      db_query("UPDATE {node_revisions} SET title = '%s' WHERE nid = %d AND vid = %d", $node->title, $node->nid, $node->vid);
    }
  }
}

this is not perfect but can avoid running the whole node_save process twice

This is indirectly related.
I'm using content profile with automatic node title.
User profiles are created upon registration, and the profile title should be the username of the user. Unfortunately, as this is during registration they are still "Anonymous" so token [user-name] still pulls anonymous. It's a question of

I'm wondering if some of the solutions for nid could be used for the username issue since it boils down to the same issue of the auto nodetitles module not having the information on node save.

StatusFileSize
new1.64 KB

Hello. I had a look at how pathauto performs its operation, which is similar, and created a solution. It's almost the same approach as in #69, but I did it without the use of node_save() in hook_nodeapi(), and I altered some other functions to compensate for this.

I am not sure if it is a good one, but have a look. I tested it locally, and it seems to work, both on node creation, update and bulk updates.

I apologize that this is not in patch form but I am at a client that only has very locked down win desktops to use for the day...

We changed the original auto_nodetitle.module function to the following:

/**
* Implementation of hook_nodeapi().
*/
function auto_nodetitle_nodeapi(&$node, $op) {
switch ($op) {
case 'presave':
auto_nodetitle_set_title($node);
break;
case 'insert':
unset($node->auto_nodetitle_applied);
if (auto_nodetitle_is_needed($node)) {
auto_nodetitle_set_title($node);
db_query("UPDATE {node} SET title = '%s' WHERE nid = %d", $node->title, $node->nid);
db_query("UPDATE {node_revisions} SET title = '%s' WHERE nid = %d AND vid = %d", $node->title, $node->nid, $node->vid);
}
break;
}
}

And saw the expected results with [term]. We had to adjust pathauto settings though, as pathauto was substituting [title-raw] without ant's [term] detokenized.

HTH.

It would be awesome if whatever fixes this nid problem also fixes the same problem with computed fields...

Subscribing.

Shouldn't all these node-based tokens issues at node creation be considered as critical for Auto Nodetitles as this crucial module eventually fails setting up the right node title in some (many) circumstances?

Every bug is critical, generally use critical for user data losing/corruption. This not the case her because nid is saved of course...
the target is not to search how we can put a bug in a "critical" state but in "reviewed & tested".

So if you would like to help and resolve this issue quickly the best way is to try the last patch #82

subscribing

subscribing too

Regarding the patch in #82:
I have not had the time to look at it more closely, but I think I experienced a situation where it did not work, so the patch is not a complete solution. Might be a basis for something though.

Status:Needs work» Needs review
StatusFileSize
new1.76 KB

I modified the patch #48 to work also with #738466: Generate node.title on validate step as well (not only on presave). I try on my own installation with success. I's not perfect but work.

For my point of view we can use auto_nodetitle_set_title($node); for all operation except "insert".

What do you think?

StatusFileSize
new1.15 KB

For me is more the right way... This one use the original function auto_nodetitle_set_title and only use additional query for insert (when we don't have the nid). I also add the operation 'presave' and 'validate' because sometimes we need the generated title in other module (pathauto, rules, token....). Of course we cannot' have the NID in presave state..

One problem I've noted with this approach is that pathauto will use 'ant-#' as the clean url for the node unless you have a path pattern explicitly set. In other words, if pathauto is trying to use the node title for the path, you will simply see 'ant-#'.

On my system with #90 I don't have the 'ant' problem (but I have without this patch) and I don't see what #91 would have.. Do you try this patchs?

Have not had a chance to generate a patch, but for those interested -- Here is the modified hook_nodeapi function, updated to handle the pathauto issue I noted above

<?php
/**
* Implementation of hook_nodeapi().
*/
function auto_nodetitle_nodeapi(&$node, $op) {
  switch (
$op) {
    case
'presave':
      if (!empty(
$node->nid) && auto_nodetitle_is_needed($node)) {
       
auto_nodetitle_set_title($node);
      }
    break;
    case
'insert':
     
// Clear the applied flag as the title saved during presave may be invalid
     
unset($node->auto_nodetitle_applied);
      if (
auto_nodetitle_is_needed($node)) {
       
auto_nodetitle_set_title($node);
       
// Update node title directly, without invoking hook_nodeapi()
       
db_query("UPDATE {node} SET title = '%s' WHERE nid = %d", $node->title, $node->nid);
       
db_query("UPDATE {node_revisions} SET title = '%s' WHERE nid = %d AND vid = %d", $node->title, $node->nid, $node->vid);
       
// Invoke pathauto for paths based on the node title
       
$placeholders = pathauto_get_placeholders('node', $node);
       
pathauto_create_alias('node', 'bulkupdate', $placeholders, "node/$node->nid", $node->nid, $node->type);
      }
    break;
  }
}
?>

Ok I see...

I don't like the "!empty($node->nid)" because most of the time we don't use nid on node title.

I also change
* add "validate" see #738466: Generate node.title on validate step as well (not only on presave)
* test if really we need to resave the title and path

<?php
/**
* Implementation of hook_nodeapi().
*/
function auto_nodetitle_nodeapi(&$node, $op) {
  switch (
$op) {
    case
'presave':
    case
'validate':
      if (
auto_nodetitle_is_needed($node)) {
       
auto_nodetitle_set_title($node);
      }
    break;
    case
'insert':
     
$old_node_title = $node->title;
     
// Clear the applied flag as the title saved during presave may be invalid
     
unset($node->auto_nodetitle_applied);
      if (
auto_nodetitle_is_needed($node)) {
       
auto_nodetitle_set_title($node);
        if(
$old_node_title != $node->title){
           
// Update node title directly, without invoking hook_nodeapi()
           
db_query("UPDATE {node} SET title = '%s' WHERE nid = %d", $node->title, $node->nid);
           
db_query("UPDATE {node_revisions} SET title = '%s' WHERE nid = %d AND vid = %d", $node->title, $node->nid, $node->vid);
           
// Invoke pathauto for paths based on the node title
           
$placeholders = pathauto_get_placeholders('node', $node);
           
pathauto_create_alias('node', 'bulkupdate', $placeholders, "node/$node->nid", $node->nid, $node->type);
        }
      }
    break;
  }
}
?>

Little fix for users without pathauto module

<?php
/**
* Implementation of hook_nodeapi().
*/
function auto_nodetitle_nodeapi(&$node, $op) {
  switch (
$op) {
    case
'presave':
    case
'validate':
      if (
auto_nodetitle_is_needed($node)) {
       
auto_nodetitle_set_title($node);
      }
    break;
    case
'insert':
     
$old_node_title = $node->title;
     
// Clear the applied flag as the title saved during presave may be invalid
     
unset($node->auto_nodetitle_applied);
      if (
auto_nodetitle_is_needed($node)) {
       
auto_nodetitle_set_title($node);
        if(
$old_node_title != $node->title){
           
// Update node title directly, without invoking hook_nodeapi()
           
db_query("UPDATE {node} SET title = '%s' WHERE nid = %d", $node->title, $node->nid);
           
db_query("UPDATE {node_revisions} SET title = '%s' WHERE nid = %d AND vid = %d", $node->title, $node->nid, $node->vid);
           
// Invoke pathauto for paths based on the node title
           
if(module_exists('pathauto')){
             
$placeholders = pathauto_get_placeholders('node', $node);
             
pathauto_create_alias('node', 'bulkupdate', $placeholders, "node/$node->nid", $node->nid, $node->type);
            }
        }
      }
    break;
  }
}
?>

Version:6.x-1.2» 6.x-1.x-dev
StatusFileSize
new1.73 KB

Patch from #96 works fine

Status:Needs review» Reviewed & tested by the community

My vote for a commit! Works fine!

Status:Reviewed & tested by the community» Closed (works as designed)

Well it works, but it directly writes to the node table, which belongs to the node module - thus that's bad style. Also this will never work with the node previews - it can't by design. So no way for this patch to go directly in the module.

Status:Closed (works as designed)» Active

oh, let's keep it at "active" so it appears as open-issue for others looking for that.

@fago: Do you know a better solution? More than 100 post because we all suffer from this issue. A lot of user tried to provide a patch or a solution. As a maintainer I think it is now time to select one approach and to commit a working solution. Because we all have to port the patch as soon as the module is upgraded.

I think there must be a solution to solve this issue, right?

@fago I think that a checkbox option with a good description (notice about preview) and readme entry is enough to solve this.
By-design means that Drupal6 have no ability to use some tokens in some states of node which is reasonable. But OTOH this works with workaround ... direct update {node} table.
Do you really sure that this edge-case require another module to add this functionality to ANT?

@fago the patch #97 is a reasonable code with measurable side effect.
Of course we can't know NID on preview on insert. This is not an issue and a short note in documentation can explain why.

If really you don't want to commit this please add a "limitation" section in the description of the module.

I have an alternative way to do this with much fewer code changes.
The downside is that it would add a dependency on another module.

This requires the Rules module.

The rules event system can respond to a node with an empty title.
The idea is to use the rules engine to:
1) If a node type is new (or not?)
2) Check to see of the content title field is empty
3) Use the rules engine to 'Set created content's title'

In the case if #1:
- This issue is a consideration: http://drupal.org/node/171249 because using rules in conjunction with this module, they will clash
- For this reason this module might need to have an option to only auto create node title on new content
- To prevent this clash from happening, you might want to set the rule to evaluate only when "content is new"

In the case of #2:
- As far as I can tell, the rules module does not provide a condition directly comparing against the content title
- My solution was to use the condition of "Check a truth value" with: <?php if ("[node:title]" == "") print ('1') else print('0'); ?>
- Another note is that rules puts a size restriction on these fields that are not sane for php scripts, try your best to keep the scripts as small as possible

In the case of #3):
- One could then set this to the same value to that of what this module should be setting this to.
- if the auto title is set to: [nid], then this rule should be set to [node:nid]

Here is my view on this:
- I like automatic node titles because it gives me the ability to hide and get rid of the built in node title.
- This gives me the ability to use a more powerful/flexible node title based on CCK
- The Rules module can be used to do everything that automatic node titles can do, except:
1) Make the built in title-field vanish
2) Automatic node titles is more appropriate for entering in custom PHP due to Rule's field size limitation (and the use of a textarea instead of a textfield)
3) Rules needs a conditional option for directly checking a content title in the same way the CCK Rules work
- If the issues with 2 and 3 were to be resolved in Rules, then this module would only need to provide for the case of #1

I was thinking that something like #104 would work also, but I was not considering depending on another module. After all, couldn't this module essentially do the same thing?

All it would need is to implement a hook when the node is displayed. If, as thekevinday suggests, the title is blank, then this module would set the value and save the node prior to display. Under most cases, the node is displayed immediately after saving it, right? That would mean that the title would (for all intents and purposes) be set during the initial save, which is what we're all looking for. There would be a small impact on page views (because of the check for an empty title), but I don't think it would be much and (I'm assuming) it would be less than the impact of the Rules module, since it'd only be checking for an empty string.

Any thoughts?

Quote from the project page:
>"auto_nodetitle" is a small and efficient module
and I want it to stay that way.

>But OTOH this works with workaround ... direct update {node} table.
Yes. It's a hack to make a special case working. But no, I won't start adding hacks for special cases. I want the module to stay small, simple and efficient.

@Rules:
To improve interoperability with Rules one could do a tiny action "Generate automatic node title" that just invokes ant's function. Or just use the "Save content" action is ant automatically runs on node-save. So to fix this issue then just add a rule that fires after node creation that invokes that action.

@Fago Come on friend. Honestly - you can not possibly support your argument that this extremely small code change is going to cause any sort of significant impact relative to code size, complexity, or efficiency. It is hands down the only way to fix this issue (and yes - it is an issue) with the smallest amount of impact and complexity as possible. If you want to make this a configurable option that is 'off' by default - I think that's reasonable. What is not reasonable is for you to call it a hack and a fringe case. Enough people have participated in and contributed to this thread for you to see it is a relevant issue that deserves attention.

Please refer to #615410: Auto Node-Title cannot use serial field -- this is another issue that would benefit from this fix. It is not simply NID that is at issue here.

I guess there is case that is against my argument in #104.

There may be cases where appropriately privileged users can create content types but do not have permissions to admin rules.
In this specific case the privileged user should be able to set the automatic node title via the content type admin menu.

Version:6.x-1.x-dev» 6.x-1.2

subscribe

Version:6.x-1.2» 7.x-1.x-dev

Don't new features go in 7.x?

Version:7.x-1.x-dev» 6.x-1.x-dev

Well... I agree that it is common practice to have new features in 7.x and then backport them to 6.x (if it is possible API-wise). Especially new features that break things or require new drupal API features in order to be implemented.

Of course it is up to the maintainers to either do that or start with a 6.x and then create a 7.x. That choice I believe is most of the times influenced by the number of people using each version. Some even choose to backport to 5.x if there is still a considerable amount of people using it. This also ensures that (actually increases the chances) there will also be enough beta-testers for the new features before they go public. More quality assurance in other words. This module has a few hundred people less then 18.000 using 6.x versions, around 1.500 using 5.x but only 1 using 7.x! ...wonder who that person is (?) :P

...see the stats for yourself here.

All the teasing aside, it is also common practice to have dev versions for people to beta-test new features. There are around 300 people using 6.x-1.x-dev of this module (including myself). Now, if the new feature brings so many changes along that it might either break things or fundamentally change the way it's been used, maintainers still might choose to increase the major version number (but not the core version number). So, you might actually see modules go from say... 6.x-1.x to 6.x-2.x.

I know you must be excited to be using D7 and desperately trying to get some attention to 7.x versions of modules, but do keep in mind that D7 is not officially out yet, which also means that it is subject to drastic API changes at any point (not a very good thing for module maintainers). Even D5 has not been kicked out of official support yet either AFAIK (still listed in drupal.org front page as an official download).

On top of that, it seems that this module's maintainers aren't in a D7 environment. I am aware that there is a 7.x-dev version available, but I don't see the #D7CX pledge to 'have a full Drupal 7 release on the day that Drupal 7 is released' in the front page. So, first sentence of this paragraph is just a reasonable assumption.

Enough arguments for you Aren?

...sorry for polluting the issue queue with such long + off-topic post as my previous one (and yet adding another useless post such as this one)

It's not a huge deal either way, but normal Drupal practice is generally to put all new changes into the latest version then backport. Since this module has a 7.x version in progress (http://drupal.org/node/770968), I figured that would be prudent at this point.

As for popularity, even if the latest version is not very popular, it can be strategically wise to force all changes into it first; otherwise you create impediments to upgrading because development priority then goes to legacy versions.

...fair enough! It is not a pure matter of popularity though. In practice, new features need to be tested extensively before they are released and that cannot be done by just a couple of people. Not even by a few dozen of them. Anyways, usually after the one is released (be it 6.x or 7.x) the other one follows in a short period of time. So, no harm I guess.

+1

This (#80) worked perfectly for me. Thanks!

@gone404: #80 is not the latest patch available.Can you please try #97 and report back?

#97 works like a charm for me! Without the patch, both the node title as well as the pathauto alias stayed blank (note: I only needed support for [term], and tested only that).

the patch in #97 didnt work form me, im using a pattern like "Someword #[nid]" and set to autonodetitle only then the title field is left empty
i used patch in #97 applied to the latest stable as of today

what did work with my pattern, and ive used it before too, is the rules fix in #30 (http://drupal.org/node/360359#comment-1460918)

i dont understand why the patch isnt working, but it doesnt enter the " if (auto_nodetitle_is_needed($node)) {" code branch when saving my content type..

edit: im falling in the edge case in the test in auto_nodetitle_is_needed()
$setting == AUTO_NODETITLE_OPTIONAL && !empty($node->title) == TRUE
to fix this, ive emptied the title before that test too, and also introduced a test to see if auto_nodetitle is actually needed (if the user didnt enter a title -> if auto_nodetitle has previously run, if he has, we need to run-fix it)

patch attached in the next reply - this fixes the case where the title is optional and auto_nodetitle runs on it (if the user hasnt entered anything) and your pattern contains other text besides [nid] that gets filled on the first run

p.s. to alleviate the (small) performance impact of this patch and get it committed i think there should be a checkbox in the content type "run on insert" or something like that, with the note that its needed to use [nid] and that it impacts performance a taddy bit, that test wont impact performance, i know this was asked before but (@fago) is this what would commit it? :) ive also read the other replies above about rules.. this just seems simpler, i dont want to install rules when i dont need to install rules, others feel the same

StatusFileSize
new1.81 KB

or option #2, instead of the checkbox, if i make a submodule that when installed would provide the above patch, would it be included in the distribution? i think checkbox would be simpler

StatusFileSize
new1.56 KB

sorry, patch in #120 is broken, seems i shouldnt edit that type directly..

just in case folks end up here, as I did, the code in #63 seems to work with the latest dev of D7 using Rules-alpha2 and auto_nodetitle dev for D7. that saved me, thanks!

#64
simply, quick & dirty
Works fine, no side effect!

@phrancescot & joya: thanx for helping here, but the way to move things is to test *latest* patches available and report back to their developers. They need people's feedback in order to fix things. Also, the workarounds you used were provided more than one year ago! A lot of things have changed code-wise since then for both this module and core.

@phrancescot: I see you report this working in d7 (while this is a 6.x issue), so most likely will have to apply #122 manually (if it applies at all). In advance, I think it will fail and possibly break things, so you'll have to do it in a non-production setup. Anyways, it will help us know if we're going to the right direction.

@joya: What version of the module and core are you using?

So, despite the fact that both of you seem to have found a solution, can you please report if #122 works or not (without #63 or #64 applied)? Thank you both in advance.

#63 was more of a workaround than anything but also applied to D7. i'm not trying this in D6, sorry if i mucked up the issue, but it applied to me even when using all the newest (D7) versions and thought it might help others to know that using rules also works. if i come across a case where i have a D6 installation and need to use NID as part of an auto_nodetitle, i'll try #122 out (which will obviously not work with the D7 version of ANT). if i get a moment, i may even do a quick D6 install with ANT and see if i can test this patch. also, if this feature makes it into the D7 version of ANT, this may also be a reasonable place to at least link to that info since a search in d.o would very likley lead one to this thread.

Patch in #122 works for me (Drupal 6.19, -dev version of ANT).

Tried it out for both auto-generation and for generation -only- if the title is left blank.

I have been using the Serial module to insert unique IDs using Autonodetitle and it works ok with a limited scope.

However a serious issue recently arose (http://drupal.org/node/606250#comment-2929218) when you have translations of nodes. Each translation is a completely new node with a different NID. It is associated with the original using TNID (translation ID), but on save, the node title should be the TNID, not the NID, so that the title does not change across translations. The solution for the Serial module is in discussion and not resolved.

The code should be modified to use TNID if a translation is being saved.

BTW, I am using the Rules module to apply the Serial ID to the node titles as explained here: http://drupal.org/node/194197#comment-2149246

Title:Use NID as node titleUse (T)NID as node title

...on save, the node title should be the TNID, not the NID, so that the title does not change across translations...

Good catch Jeff!

Each translation is a completely new node with a different NID.

BTW, I think that this will not be an issue in D7 if one uses Content translation and Title as well. This way, translations of content are not new nodes. So, you'll only have to set actual content (node body) to be translatable and node title to not be translatable. I thought I'd mention this because I just started testing these in D7 (see this issue #924968: Initial work) and thought if it is not too late (you have no deadlines and the such), perhaps then you could switch to D7 and give these a try ;)

<?php
  $lastNodeID
= db_query("SELECT nid FROM {node} order by nid DESC limit 1 ")->fetchField() + 1;
  echo
$lastNodeID;
?>

This is a modified version for Drupal 7. Still this might not give the correct NID, but works for lower frequented sites.

Version:6.x-1.x-dev» 6.x-1.2

#96 code update

<?php
/**
* Implementation of hook_nodeapi().
*/
function auto_nodetitle_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  switch (
$op) {
    case
'presave':
    case
'validate':
      if (
auto_nodetitle_is_needed($node)) {
       
auto_nodetitle_set_title($node);
      }
    break;
    case
'insert':
     
$old_node_title = $node->title;
       
auto_nodetitle_set_title($node);
        if(
$old_node_title != $node->title){
           
// Update node title directly, without invoking hook_nodeapi()
           
db_query("UPDATE {node} SET title = '%s' WHERE nid = %d", $node->title, $node->nid);
           
db_query("UPDATE {node_revisions} SET title = '%s' WHERE nid = %d AND vid = %d", $node->title, $node->nid, $node->vid);
           
// Invoke pathauto for paths based on the node title
           
if(module_exists('pathauto')){
             
pathauto_nodeapi($node, 'update', $a3, $a4);
            }
        }
    break;
  }
}
?>

works for me.

#131 works for me too

@phrancescot
I'm a little confused how exactly to get this to work in D7 (based on #63), and other solutions in this post are not working for me. Can you tell me what php code you placed in the pattern box? Many thanks!

My apologies: I should have edited this comment, rather than posting a new one.

phrancescot: I have set up Rules as described in #63 for D7, but I can't seem to get the Title to show the NID on the first go-round (which seems to be the issue with simply using the replacement token). If I go into the node and edit and save, the NID shows up. How did you get this to work?

#131 works for me. THX!

Easiest way to get tokens executed which are missing at insert time is calling auto_nodetitle_operations_update(array($node->nid)); as mentioned in #63.

If you don't have the Rules module enabled you may use the following code in a custom (own) module:

<?php
/**
* Implementation of hook_nodeapi().
*/
function custom_helper_nodeapi(&$node, $op, $teaser = NULL, $page = NULL) {
  switch (
$op) {
    case
'insert':
     
// get tokens executed which are missing at insert time
     
auto_nodetitle_operations_update(array($node->nid));
      break;
  }
}
?>

Version:6.x-1.2» 7.x-1.0-alpha1

Here is what I'm instructed to do by chx to have node titles like "Foo #[node:nid]" in D7:

<?php
/**
* Implements hook_node_insert().
*
* @see mymodule_exit()
*/
function mymodule_node_insert($node) {
 
// Some serious mind-blowing hack needs to be done here. Since the
  // auto_nodetitle.module does its job in hook_node_presave(), a node can't
  // have a title like '[node:type] #[node:nid]', as $node->nid is not yet
  // available there. Calling node_save() here in hook_node_insert() would
  // mean a PITA since it could mean an infinite loop. So the trick is to save
  // the affected nids temporalily in a drupal_static(), and resave the nodes
  // with their titles corrected in hook_exit(). Kudos to chx et al.
 
if ($node->type == 'mycontenttype') { // As this needs to be done only for this content type of mine.
   
array_push(drupal_static('mymodule_nids', array()), $node->nid);
  }
}
/**
* Implements hook_exit().
*
* @see mymodule_node_insert()
*/
function mymodule_exit() {
  foreach (
drupal_static('mymodule_nids', array())) as $nid) {
   
$node = node_load($nid, NULL, TRUE);
   
$node->title = 'Foo #' . $node->nid;
   
node_save($node);
  }
}
?>

One more thing to be said: this is tested and working well, but is not nice. Anyways, we couldn't invent a nicer way to achieve the same.

Your problem is more than an infinite loop which can be easily fixed by a mutex, the problem is that firing another node_save from inside node_save on the same node will quite probably result in update hooks running before insert hooks of all sorts and that will surely break. You need to fire the second node_save outside of node_save and the only hook to fire 100% outside of node_save hook_exit. There's nothing else you can rely on.

#131 only works on nodes with automatitic nodetitles enabled. On nodes with automatic nodetitles disabled the title field does not save correctly. It generates a title even tought this feature is disabled.

#63 works correctly but the nid update takes time. I have a Rule that automaticly redirects when the node is saved. The information message (... node has been saved) does not show the correct title (nid is missing).

I create another issue post, http://drupal.org/node/1204728 and only focus on drupal 7 using RULES module. Current post is mixing drupal 6 and 7 possible solution and getting a bit confusing.

Update: #63 work on drupal 7 too. :)

This solution (#136) worked for me!

I used the technique suggested in #63, using Rules to set the node title to NID after node save, successfully for a while and then I added another action to the same triggered rule to set some other field in CCK. After that, the node autotitle (NAT) action stopped working. Reordering the actions didn't fix it. I tried putting the NAT action in its own triggered rule but that failed too. Not sure why adding additional actions triggered on node save conflict with auto_nodetitle_operations_update(array($node->nid));

My work around was to change the Rules action to "Set Content Title" using the [node:nid] token, and also set the NAT title field in the content type to [nid]. So the Rules action sets the title to the saved node ID, and then NAT takes over after that. This works ok for ordinary single language sites but if you have a multi-lingual site and wish to maintain the title across translations (as I noted in #128) you'll have to do this a different way because tnid is not available as a token, as follows:

Use the Rules action, "Execute custom PHP code" and enter this code (Don't use PHP tags here):

if ($node->tnid == 0)
$node->title = $node->nid;
else
$node->title = $node->tnid;
return array("node" => $node);

Then, in the configuration section for node autotitle in your content type, enable PHP evaluation and enter this code (You must use PHP tags here):
<?php
if ($node->tnid == 0)
return (
$node->nid);
else
return (
$node->tnid);
?>

The code in the node autotitle config section is necessary because without it, NAT will change the title to nid when you subsequently resave or publish the node. I guess you could always create a tnid token using the Custom Tokens module if you wanted to go that route.

I noticed the version for this thread is 7.x-1.0-alpha. I did this on 6.12.

My setup is:

Drupal 6.22
Automatic Nodetitles 6.x-1.2

I don't want to use modules Rule, Tokens or patching the existing module files.

I use this code in the Pattern for the title (with Evaluate PHP in pattern enable):

<?php
$n
= node_load($node->nid);
if (
$n->title) {
   echo
$n->title;
} else {
  
$ts_row = db_fetch_array(db_query("SHOW TABLE STATUS LIKE 'node'"));
   echo
$ts_row['Auto_increment'] ;
}
?>

At last it works. This is inspired from comment #44 but using db_ instead of mysql_

#63 works for d7

Hi, i use this code inside "pattern for the title"

<?php
$value
= db_query("SELECT nid FROM {node} ORDER BY nid DESC LIMIT 1")->fetchField();
$numero=strval($value);
$numero2=intval($numero)+1;
print
$numero2."AFKDR";
?>

auto node title 7.x-1.0
drupal 7.10

@chx, #137
Thanks for weighing in on this!

This is the solution I was looking for.

Also in regards to #137:

If you are using auto_nodetitle and want your messages to reflect it, ie: "Foo #123 was created" modify as follows:

<?php
/**
* Implements hook_node_insert().
*
* @see mymodule_exit()
*/
function mymodule_node_insert($node) {
 
// Some serious mind-blowing hack needs to be done here. Since the
  // auto_nodetitle.module does its job in hook_node_presave(), a node can't
  // have a title like '[node:type] #[node:nid]', as $node->nid is not yet
  // available there. Calling node_save() here in hook_node_insert() would
  // mean a PITA since it could mean an infinite loop. So the trick is to save
  // the affected nids temporalily in a drupal_static(), and resave the nodes
  // with their titles corrected in hook_exit(). Kudos to chx et al.
 
if ($node->type == 'mycontenttype') { // As this needs to be done only for this content type of mine.
    // modify node title to provide proper message
   
auto_nodetitle_set_title($node);
   
array_push(drupal_static('mymodule_nids', array()), $node->nid);
  }
}
/**
* Implements hook_exit().
*
* @see mymodule_node_insert()
*/
function mymodule_exit() {
  foreach (
drupal_static('mymodule_nids', array())) as $nid) {
   
$node = node_load($nid, NULL, TRUE);
   
// $node->title = 'Foo #' . $node->nid;
    // if using auto_nodetitle it will set the title during save
   
node_save($node);
  }
}
?>

An alternative work around for anyone interested using rules..

I attempted to use the "Before saving content" and "After saving new content" rules to set the NID in the title but I kept getting errors or nothing at all..

The solution I found was to create a rules component with a "Set data value" to update the title..
Then schedule the component with a "After saving new content" rule using Rules Scheduler to run "now +1 minute" so it runs on the next cron run automatically.. In testing it seems to have worked..

solution #145

i think this is better:

<?php
if (!isset($node->nid)) {
 
$value = db_query("SELECT nid FROM {node} ORDER BY nid DESC LIMIT 1")->fetchField();
 
$numero=strval($value);
 
$numero2=intval($numero)+1;
  print
'your text ' . $numero2;
} else {
print
'your text '  . $node->nid;
}
?>

That approach is simply not robust. If you have a busy site it is possible a node will be created between the time you query and the time you set the title. It may be very unlikely but I see no reason not to go with chx's solution.

+1 #137

Drupal 7.15 and auto_nodetitle 7.x-1.0

Thanks chx!

Re: #137, drupal_static() didn't work for me. I ended up saving the list in $_SESSION. If you do that, don't forget to unset it. See #1445124: Add support for entity id tokens during creation

Awesome, #19 worked splendidly for D6. I'm on D6.28, Auto Node Title 6.x-1.2

D7 users should consider switching to Automatic Entity Label. The latest dev allows you to use [node:nid] in the node title. See http://drupal.org/node/1445124.

#63 solved my issue :)

#63 solved my issue too!

Thanks @Sarenc! #147 is a great solution that worked perfectly for me. You saved me hours!

Complete hack here. I am going to try #63, but before I found this thread, I used the following with ANT:

<?php
  
// return '<pre>'.var_export($_POST, true).'</pre>'; // Use this to find below values
  
return $_POST['FIELD_NAME']['und'][0]['WIDGET NAME'];
?>

Flame away - this is about as bad a hack as it gets, but it completely works for me. This is on D7.