Hi,

I'm trying to store a new comment through comment_save, but I'm experiencing two problems.

1. Undefined stdClass::$cid
In comment_save() there is a check like this:
if ($comment->cid) { (line 1470 in comment.module
But on a new comment, cid wont exists and therefore an undefined notice is shown. A better solution would be if (isset($comment->cid)) { maybe?

2. How do I get the cid on the newly created comment?
comment_save() doesn't return anything.
Neither does it take the $comment as a reference.
So I can't see how I would get the cid of the newly created comment?
comment_save() is setting $comment->cid, but since it isn't passed as an reference I can't access this - but it is passed correctly to hook_comment_insert.

How do I get access to the cid?

Comments

Anonymous’s picture

I think objects are passed by reference in PHP (http://php.net/manual/en/language.oop5.references.php goes into it in more depth). Once you've called comment_save($comment) the object should have a populated cid. If it doesn't just grab it from the db directly:

$comment->cid = db_query('SELECT MAX(cid) FROM {comment}')->fetchField();
mtrolle’s picture

You are absolutely correct regarding the object. It must be another issue in my code.
But you solution with a new query isn't safe on a highload envoirement, as I could then get the id of another node than mine.

Jaypan’s picture

But on a new comment, cid wont exists and therefore an undefined notice is shown. A better solution would be if (isset($comment->cid)) { maybe?

If $comment is an object, then if($comment->cid) won't throw any notices, and therefore is fine code. Your problem isn't that $comment->cid doesn't exist (it shouldn't exist when you are saving a new comment), it's that you aren't properly passing an object to comment_save().

mtrolle’s picture

I'm sure I'm passing an object.
I get the following notice:

Notice: Undefined property: stdClass::$cid in comment_save() (line 1470 of /htdocs/drupal/modules/comment/comment.module).
Jaypan’s picture

Maybe. Throw a quick test into the top of comment_save():

(is_object($comment)) ? die('is object') : die('not object');

This will tell you if it's a proper object or not.

mtrolle’s picture

Regarding 2. getting the cid of a newly created comment, it works. It was a bug in my code.
But regarding 1. the undefined stdClass::$cid when checking if there should be created a new comment or if it is an edit of an existing, this I believe is an issue.
It works perfectly fine when I add an isset()

Thanks for you help.

jibinlonga’s picture

if you used comment_save($comment), you can check $comment->cid.
It have changed.