Jump to content

Is It Possible To Add A 'comment' Programmatically?


applab
 Share

Recommended Posts

I have a template which includes a "comments" field using the core Comments field type (FieldtypeComments)

Is there a way to post a comment to a page which uses this field, programmatically, from a different page?, ie. not the current $page.

something along the lines of:

$my_comment = array(
    'cite' => $comment_cite,
    'text' => $comment_text,
    'created' => $comment_date
);

$p = $pages->get('my-selector');
$p->comments->add($my_comment);    // no such method!

tia.

Link to comment
Share on other sites

Something like this should work (assuming that the name of your comments field is 'comments'):

$comment = new Comment;
$comment->text = "my text";
$comment->cite = "my name";
// etc.

$p = $pages->get('/about/');
$p->comments->add($comment);
$p->save('comments');
  • Like 5
Link to comment
Share on other sites

thanks Teppo, worked great after 1 amendment:

on first attempt I got an error:

"Error: Exception: Can't save field from page 1028: /blog/posts/test-post/: Call $page->setOutputFormatting(false) before getting/setting values that will be modified and saved."

so, I did as the error suggested end ended up with:

$comment = new Comment;
$comment->text = "my text";
$comment->cite = "my name";
// etc.

$p = $pages->get('/about/');
$p->setOutputFormatting(false);    // added
$p->comments->add($comment);
$p->save('comments');

checking the PW cheatsheet for $page->setOutputFormatting() makes it clear why that's needed.

  • Like 5
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...