I have threaded comments on a site where there are two roles, reviewers and administrators.
Comments are shown in a view block added to the node (in this case a webform). The view format is set to 'content' and it's using tag based caching.
- Admins are allowed to see all comments
- Reviewers can write comments and only seen their own, or replies to them
This is all ok and I've implemented it with hook_ENTITY_TYPE_view_alter
(simplified example below).
The problem is caching - the view for one reviewer is being cached and shown when the other logs on.
Scenario:
- Alice and Bob are reviewers
- Alice leaves a comment on a node. Logs out.
- Bob logs on. If the cache hasn't been cleared in the meantime, he'll see Alice's comments even though he shouldn't. (And then, were I then to clear the cache, his view would be correct, but should he logged off and Alice logs back in, she'll now see the view intended for Bob.)
Can I give each user their own cache, or failing that, not cache the view at all? (setting caching of the view block to 'none' doesn't appear to change anything, would be useful to know why in answer.)
function mymodule_comment_view_alter(
&$build,
Drupal\Core\Entity\EntityInterface $entity,
\Drupal\Core\Entity\Display\EntityViewDisplayInterface $display ) {
// ... some logic that deals with admins (omitted)
$comment_uid = $entity->getOwnerId();
$parent_comment = $entity->getParentComment();
if ( $comment_uid === $current_user->id() ) {
// current user's own comment? Show it
} elseif ( isset( $parent_comment ) &&
$parent_comment->getOwnerId() == $current_user->id() ) {
// a comment in reply to current user's comment? Show it
} else {
// otherwise, don't show it
$build['#access'] = false;
}
return;
}
user
?