2

I've made my own module to add commenting to a node (it opens modally in a colorbox - really nice). The form works great, but how do I save the comment?

I know it's got to be done using comment_save. But, as usual, drupal.org is great at showing the code for the function without giving an example...

Has anyone done this before?

I'm guessing it's something like:

$comment = new stdClass();

$comment->nid = $the_node_the_comment_is_for;
$comment->title = $my_comment_title;
$comment->body = $my_comment_body;

comment_save($comment);

1 Answer 1

5

Yes you can save comment dynamically using comment_save() function, a working example is given below

<?php

$comment = new stdClass();

$comment->nid = 28; // nid of a node you want to attach a comment to
$comment->cid = 0; // leave it as is
$comment->pid = 0; // parent comment id, 0 if none 
$comment->uid = 1; // user's id, who left the comment
$comment->mail = '[email protected]'; // user's email
$comment->name = 'User name'; // If user is authenticated you can omit this field, it will be auto-populated, if the user is anonymous and you want to name him somehow, input his name here
$comment->thread = '01/'; // OPTIONAL. If you need comments to be threaded you can fill this value. Otherwise omit it.
$comment->hostname = '127.0.01' ;// OPTIONAL. You can log poster's ip here
$comment->created = time(); // OPTIONAL. You can set any time you want here. Useful for backdated comments creation.
$comment->is_anonymous = 0; // leave it as is
$comment->homepage = ''; // you can add homepage URL here
$comment->status = COMMENT_PUBLISHED; // We auto-publish this comment
$comment->language = LANGUAGE_NONE; // The same as for a node
$comment->subject = 'Comment subject'; 
$comment->comment_body[$comment->language][0]['value'] = 'Comment body text'; // Everything here is pretty much like with a node
$comment->comment_body[$comment->language][0]['format'] = 'filtered_html'; 
$comment->field_custom_field_name[LANGUAGE_NONE][0]['value'] = 'Some value'; // OPTIONAL. If your comment has a custom field attached it can added as simple as this // preparing a comment for a save

comment_submit($comment); // saving a comment
comment_save($comment);
?>

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