I want to add comment by php script. Here is my code:

$comment = new StdClass();
$comment->nid = 1;
$comment->status = 1;
$comment->created = time();
$comment->changed = time();
$comment->subject = 'test';
$comment->name = 'admin';
$comment->language = 'und';
$comment->comment_body = 'test';
comment_save($comment);

It seems "comment_body" has been removed in Drupal 7. Comments text are now entity. But I am not familiar with entities. Can someone please tell me how can I add text to the new comment?

Comments

Anonymous’s picture

Something like this would probably do it:

$comment->field_body = array(
  'und' => array(
    0 => array(
      'value' => 'YOUR COMMENT BODY HERE'
    )
  )
);

It's untested so let me know if it doesn't work, it'll be something very similar to that though

Mamouri’s picture

Thank for the help, But it did not work either. filed_body exist in variable returned by comment_load function, but it's completely ignored when it pass to comment_save function.

Here is result of comment_load:

stdClass Object
(
    [cid] => 1
    [pid] => 0
    [nid] => 31
    [comment_body] => Array
        (
            [und] => Array
                (
                    [0] => Array
                        (
                            [value] => TEST
                            [format] => filtered_html
                            [safe_value] => TEST
                        )

                )

        )

Comments in Drupal 7 are now an entity, hence function _comment_body_field_create create a comment_body field. I am not familiar with Field API or Entity API and I don't know how can I create a new entity and attach it to the comment.

Mamouri’s picture

I manage to do it. Here is the code:

function send_comment($bcomment, $node) {
	$comment = new StdClass();
	$comment->nid = $node->nid;
	$comment->uid = $this->user;
	$comment->u_uid = $this->user;
	$comment->status = 1;
	$comment->created = time();
	$comment->changed = time();
	$comment->subject = $bcomment['subject'];
	$comment->language = 'und';
	comment_save($comment);
	
	// add comment text, field type
	$comment = comment_load($comment->cid);
	$comment->comment_body = array(
		'und' => array(
			0 => array(
				'value' => $bcomment,
				'format' => 'filtered_html'
			)
		)
	);
	$comment->field_type = array(
		'und' => array(
			0 => array(
				'value' => $bcomment['type'],
				'format' => 'filtered_html'
			)
		)
	);
	comment_save($comment);
	return $comment->cid;
}
danylevskyi’s picture

Here is a most important part of the working code to submit a comment programmatically.
http://d.danylevskyi.com/node/8