Ning Components: XNC_Comment
A long time ago, when I first started working in the Ning playground, the first thing that impressed me about it was the fact that it had ready built components for so much *stuff*. Comments. Ratings. Flickr. Amazon. Calendars. Questionairres (Which is a very difficult word to spell right.)
Last night, after setting up X\_Query, I thought “hm, what if people want to comment?” And as I did, I remembered those components. I went into the developer documentation and looked up XNC\_Comment, which had a great, simple example of how to add comments to any content object.
But I didn’t have any content objects. The app is built as an API, so there was no need for Content Objects (at least not until I build up the documentation).
So I built a couple quick lines to add Content where I need it:
<?php
$d = XN\_Query::create(‘content’)->filter(“owner”)->filter(“type”, “=”, “Page”)->filter(‘title’, ‘=’, $\_SERVER[‘SCRIPT\_FILENAME’])->uniqueResult();
if (!$d) {
$d = XN\_Content::Create(“Page”, $\_SERVER[‘SCRIPT\_FILENAME’]);
$d->save();
}
?>
Once this is done, the $d is an object for the current page. Once you’ve done that, you can just slightly modify the example from XNC_Comment:
require\_once ‘XNC/Comment.php’;
$newComment = new XNC\_Comment($d);
// Handle any form submission of adding a new comment
if ($newComment->willProcessForm()) {
$newComment->processForm();
} elseif ($newComment->lastError() != XNC\_Comment::ERROR\_FORM\_ABSENT) {
print $newComment->lastError();
}
// Display the add a comment form (unless it was just submitted and saved)
if ($newComment->canProcessForm()) {
echo $newComment->buildForm();
}
// Display a list of comments belonging to a parent object
if ($d->my->content($newComment->referenceAttribute,true)) {
foreach ($d->my->content($newComment->referenceAttribute,true) as $comment) {
echo new XNC\_Comment($comment);
}
}
Now, you’ve got comments on any page you want! Just include these two chunks of code at the bottom of each page. This is one of the easiest things I’ve done. Now anyone can take these code snippets and use them in any Ning app. Hm… maybe the next step is to build a code snippets repository…