I am trying to hide the comment box for anonymous users. Anonymous users should only be able to view the comments. How can I hide the comment form?
2 Answers
The comment module provides a permission, "Post comments" (post comments
). Before using any code option, you should remove that permission for anonymous users.
I added this inside my hook and it worked:
if($form_id == 'comment_comment_form')
{
if (\Drupal::currentUser()->isAnonymous())
{
$form['comment_body']['#access'] = FALSE;
}
}
-
If the default "Post comments" permission isn't enough to handle your needs, you should consider creating your own permission in a custom module and checking if the user has the permission (vs checking for a specific role). It's pretty easy to add a permission, see: drupal.stackexchange.com/a/214501/48114– sonfdCommented Jan 20, 2021 at 1:13