Comments Work v1.1.5
Easy to use commenting for Craft CMS
More Craft plugins

Events

Customize with events

You can customize comments work with events.

An example would be to disallow posting on content that was created more than a year ago.

Or you could add a lightswitch field to your content items so editors can specify wether commenting is allowed.


The `Can Post` event

With this event you can programmatically determine wether a user (or anonymous user) can post on a specific element.

Here's a complete example how to integrate the event in Craft's default module that ships with a fresh install.


Twig: show a message if a user is not allowed to post
_entry.twig:
{% set commentsWork = craft.commentsWork.service %}
{% set canComment = commentsWork.canComment(entry, currentUser) %}
{% if not canComment.allowed %}
	<p>{{ canComment.message }}</p>
{% else %}
    // show the comment form
{% endif %}
Module: disallow commenting on posts older than one month
modules/module.php:
// don't forget to bootstrap the module in config/app.php !!

namespace modules;

use Craft;
use craft\elements\Entry;
use twentyfourhoursmedia\commentswork\events\AllowedEvent;
use twentyfourhoursmedia\commentswork\services\CommentsWorkService;
use yii\base\Event;

class Module extends \yii\base\Module
{

    public function init()
    {
        // Set a @modules alias pointed to the modules/ directory
        Craft::setAlias('@modules', __DIR__);

        // Set the controllerNamespace based on whether this is a console or web request
        if (Craft::$app->getRequest()->getIsConsoleRequest()) {
            $this->controllerNamespace = 'modules\\console\\controllers';
        } else {
            $this->controllerNamespace = 'modules\\controllers';
        }
        parent::init();
        
        // Check if a user can comment on an element
        Event::on(CommentsWorkService::class, CommentsWorkService::EVENT_CAN_COMMENT, function(AllowedEvent $event) {
            // $event->user contains the user that wants to comment, or null for an anonymous user
            // $event->element contains the element to post comments on

            // example: disallow posting on elements that are posted more than one month ago
            // prevent other listeners from setting 'handled' to another value
            if ($event->element instanceof Entry && $event->element->postDate->getTimestamp() < strtotime('-1 month')) {
                $event->allowed = false;
                $event->message = 'You cannot post comments on old content.';
                $event->handled = true;
            }
        });
        
    }
}