I have custom code in the footer of a view which is designed to load a node (the node id is passed to the view as an arguement), make some changes to the node (change its status to published and also assign the current user as its author) and then save the node. I am using the code below and for some reason, the code consistently modifies the node status correctly but only sometimes does the node author change. I cannot yet find any consistent reason for the inconsistency but perhaps someone can help figure out the error in my ways.
Thanks
PS: A little background as to what I am trying to accomplish. I have a content type which can be created by anonymous users. However, once this content is created, there is a rule which prompts the user to create an account. Only if the user creates an account does the newly created content become published and this code is necessary to update the created content to reflect the new user as its author
/*
Set newly created user as publisher of newly created node and set node to published status
*/
global $user;
$view = views_get_current_view();
$arg1 = $view->args[0];
$node = node_load(array("nid" => $arg1));
print "Node Status was: ".$node->status."<br />";
$node->status = "1";
print "Node Status is now: ".$node->status."<br />";
print "Node Author was: ".$node->uid."<br />";
$node->uid = $user->uid;
print "Node ID: ".$node->nid."<br />";
print "Current User ID: ".$user->uid."<br />";
print "Node Author ID is now: ".$node->uid."<br />";
node_save($node);
The really weird thing is that I have a couple Print statements in the code so that I can have feedback on the code logic. This feedback verifies that the $node->uid has indeed been updated to the correct value, however, when I check the node itself it still lists "anonymous" as the author meaning that the node_save function somehow resets $node->uid before saving.
Comments
I seem to recall you need to
I seem to recall you need to set $node->name, in this case to $user->name.
Yes, I did try that but it
Yes, I did try that but it still does not work. Interestingly, I did a
var_dumpof $node and the correct values are in there. But the node author just does not update.Solved It
Ok, I figured it out. You have to call node_submit before node_save to get everything to work (also a good idea to set $node->name as well) e.g.