Something is baffling me. I have this view of streams to users. An admin may make a stream to themselves, a specific person or everyone. I also have this code in which a non-admin user may see only the streams made to everyone and that specific user, whereas an admin should be able to see all streams, including the ones made to themselves. I’ve edited my code many times, but no matter what I do, I can’t get the non-admin user to see the streams to themselves. Could you maybe take a look at it and point me in the right direction? Thanks a lot in advance :slightly_smiling_face:

function hajans_crm_views_pre_render(ViewExecutable $view) {
  if (isset($view) && $view->storage->id() == 'crm' && $view->current_display == 'streams_user_tab') {
    foreach ($view->result as $index => $value) {
      $current_user = User::load(Drupal::currentUser()->id());
      if (!$current_user->hasRole('administrator')) {
        $field_to = $value->_entity->field_to->value;
        if ($field_to != 'Everyone' && $field_to != 'Myself') {
          if ($current_user->id() !== $value->_entity->uid->target_id) {

1 Answer 1


Trying to restrict access in hook_views_pre_render() isn't going to work because the view could be cached incorrectly and lots of other things could go wrong. In general, you never want to restrict access in the render pipeline, which includes the pre_render() processing.

Instead, you should define a custom views access plugin as described by Badzilla here and Lullabot here.

In general, from Drupal 8 onward, if you're trying to restrict access, look for a plugin-based solution first and then, if you can't find one, an access hook solution.

  • I'll try them and let you know which one worked for me, thanks.
    – Kartagis
    Commented Oct 14, 2022 at 9:19
  • Now that I think about it, wouldn't an access plugin restrict access to the view itself? I wish to do so for only a few rows.
    – Kartagis
    Commented Oct 14, 2022 at 13:59
  • 1
    @Kartagis If you want to restrict access to content entities, then I misread your question. In that case, you can't do that in Views, either-- you need to do it at the entity level. (Even if you configure a view to avoid showing users data you don't want them to see, they will still have access to it unless you restrict it at the entity level.) Commented Oct 14, 2022 at 15:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.