For example, in an app I am developing I have two people nodes and they get married, so i have all the info I need to automatically create a new node wich is an alias for the female node with her new married name, without any forms, i.e. no interaction with users. So I tried to call some functions to insert the new node:
//we have all the data we need to create the node....
$alias->surname = $p1->surname;
$alias->first_name = $p2->first_name;
$alias->middle_names = $p2->middle_names;
$alias->salutation = 'Mrs';
$alias->base_nid = $p2->nid;
//so we create it
global $user;
$alias->uid = $user->uid;
node_object_prepare($alias);
node_validate($alias);
node_submit($alias);
node_save($alias);
I think I have included every function i can find :-D
the node is inserted OK but it is not published, even though the workflow defined for that node type is to publish it. (Nor does it have a user-id associated with it unless I manually force it as above - it is created by "anonymous").
Seesm to me I am kludging this and there ought to be an "offical" API somewhere.
Any ideas?
Comments
A few pointers
node_object_prepare is part of loading a node so you do not need to call it when saving a node).
Calling node_validate without checking for errors has no benefit, node_submit returns a value and you need to set the status to have it show as published. Taking these all into account your code might look like
You might also want to set $alias->title if you want to be able to "find" the node in the administrative listing of content.
many thanks for the
many thanks for the feedback. i forgot about form_get_errors, thanks.
yes I kludged the status = 1 but it isn't really the answer. status=whatever the workflow is defined for the node type (which is 'person', same as the person we are aliasing). it may or may not be "1".
the real answer to the question is, I suspect, that there is no "official" API for adding a node, only for processing a form. I wonder if there is a kludge to get the current workflow?
You could use this code from node.php
Replacing
$alias->status = 1; // Publish the nodewithand it will honor the settings for the content type.
Also, I noticed you are not setting $alias->type, this needs to be set to the node type before this piece of code will work correctly.
the more people extend Drupal the more a formal API is needed
Great, many thanks for that.
You can see my point though, eh? the more people extend Drupal the more this kind of formal API will be required...