I built a custom module for the purpose of providing moderators with the ability to unpublish (or 'unapprove') a comment by clicking a link that appears on the comment.
The module provides the link and I have the template displaying it. But clicking the link appears to reroute to the page without unpublishing the comment.
- No related errors appear in the log
- This is Drupal 10.3.0
- The module machine name is unpubcomms
So I seem to be missing something. I'm sure there are other problems here. I have only written a couple of super-basic custom modules before--and only with a lot of help.
This is the .module file.
<?php
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Session\AccountInterface;
use Drupal\comment\Entity\Comment;
/**
* Implements hook_comment_links_alter().
*/
function unpubcomms_comment_links_alter(array &$links, Comment $entity, array &$context) {
if ($entity->isPublished() && \Drupal::currentUser()->hasPermission('administer comments')) {
$links['unpublish'] = [
'title' => t('Unpublish'),
'url' => \Drupal\Core\Url::fromRoute('unpubcomms.comment_unpublish', ['comment' => $entity->id()]),
];
}
}
/**
* Access callback for the comment unpublish route.
*/
function unpubcomms_comment_unpublish_access(Comment $comment, AccountInterface $account) {
return AccessResult::allowedIf($account->hasPermission('administer comments') && $comment->isPublished());
}
This is the routing.yml file.
unpubcomms.comment_unpublish:
path: '/comment/{comment}/unpublish'
defaults:
_controller: '\Drupal\unpubcomms\Controller\UnpubcommsController::unpublish'
_title: 'Unpublish Comment'
requirements:
_permission: 'administer comments'
This is the UnpubcommsController.php file.
<?php
namespace Drupal\unpubcomms\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\comment\Entity\Comment;
use Symfony\Component\HttpFoundation\RedirectResponse;
class UnpubcommsController extends ControllerBase {
/**
* Unpublishes a comment.
*
* @param \Drupal\comment\Entity\Comment $comment
* The comment to unpublish.
*
* @return \Symfony\Component\HttpFoundation\RedirectResponse
* A redirect back to the commented entity.
*/
public function unpublish(Comment $comment) {
// Unpublish the comment.
$comment->setPublished(FALSE);
$comment->save();
// Redirect back to the content entity.
return new RedirectResponse($comment->getCommentedEntity()->toUrl()->toString());
}
}
I'm guessing I've overlooked something really basic, but I'm not seeing it.
$comment->save()
, what do you see?