How to publish node from php code? Tried simple query db_query("UPDATE {开发者_Python百科node} SET status = 1 WHERE nid = %d", $nid);
but it doesn't work.
My scenario: By default nodes are unpublished. I'm altering edit-node form to add textfield. If user enters right code node become published. So I adding another submit function in form_alter and in that function checking code and if it's right trying to update node status to published.
<?php
// load the node object
$node = node_load($nid);
// set status property to 1
$node->status = 1;
// re-save the node
node_save($node);
?>
Also, I saw your comment of using $form['nid']['#value']. Are you sure that variable holds the node ID value? Usually you would be executing code on the submit handler of a form, which means you would be using something like: $form_state['values']['nid'] to get the value of the $form['nid'] element.
Example:
<?php
function mymodule_myform() {
$form = array();
$form['nid'] = array(
'#type' => 'textfield',
'#title' => 'Node ID to Publish'
);
$form['submit'] = array('#type' => 'submit', '#value' => 'Submit');
}
function mymodule_myform_submit($form, &$form_state) {
$node = node_load($form_state['values']['nid']);
if ($node) {
$node->status = 1;
node_save($node);
}
}
It's best practice not to code against the db schema directly as writing queries yourself introduces redundancy. You should always use the node API.
Drupal invokes the node api when performing a node save. This gives all the other modules in your application a chance to modify the node in any way they wish. So, it may be likely that your code is working correctly just not as you expect. For example, another module could set the node status after you set it and over write your value.
This might be a little hard to debug. You could try changing the weight of the module your code runs in to be called after everything else. This is one of the few exceptions where you can modify the database schema directly (there is a module that exposes module weights in the UI but this is a terrible idea). I don't particularly like relying on module weights to get code to work. You could end up with race conditions but this will at least identify this as the cause.
See:
http://api.drupal.org/api/drupal/modules--node--node.module/function/node_save/6
Try using the node_load
and node_save
functions built in to drupal.
Check that your custom module/theme enabled.
I would also try to create a node through Drupal interface (make it unpublished). Then run
db_query("UPDATE {node} SET status = 1 WHERE nid = %d", [paste_just_created_node_id_here]);
in your custom module and see if this works.
精彩评论