0

I can easily check if a user is logged in in most templates by simply using a twig variable, or making a custom one myself. My issue is that I would like to be able to check if a user is logged in inside a custom text field in a view.

I used

{% if logged_in %}
     Test
{% endif %}

But it didn't seem to work. Also

{{ dump(logged_in) }}

came up null. Also I looked in the available options for context filters and relationships but nothing seemed to have anything to do with the current user. Only authors of the content. Is there a way to know if the user is logged in from a view?

I suspect that it might be possible with some preprocess hook for views but if that can be avoided by using an option in views that would be preferable.

For clarification this is a view that displays a list of articles. Each with an image, title, and a snippet of body text. The article node has a field deciding whether a user login is required. If the user login is required then the body text is replaced for anyone that isn't logged in.

UPDATE: I attempted adding the variable in a preprocess hook but that didn't seem to do anything either.

function mymodule_preprocess_views_view_field(&$variables){
    $variables['logged_in'] = (\Drupal::currentUser()->isAnonymous())?false:true;
}

But {{ dump(logged_in) }} still came up null.

  • What about adding your custom text field to a views attachment and limiting the permissions on the attachment instead of mixing permissions on your main view? – lynbermt Oct 30 '17 at 17:33
  • My view is a list of articles that show an image and part of the body. Each article may or may not require a user to be logged in. If the individual article requires a login the body text is replaced. It's not an all or nothing thing. Unless a views attachment can handle that situation. – Matt Oct 30 '17 at 17:37
  • Views attachment won't handle that. I'd go back and debug the logged_in check in your twig file or put it in a preprocess. Twig would be my vote. – lynbermt Oct 30 '17 at 17:47
  • lynbermt do you know of a good preprocess function to put that in? I made an attempt above but still had no luck – Matt Oct 31 '17 at 21:17
1

I managed to accomplish this task by creating my own custom view field plugin

in mymodule.views.inc I used

function mymodule_views_data() {

  $data['views']['table']['group'] = t('Current User');
  $data['views']['table']['join'] = [
    // #global is a special flag which allows a table to appear all the time.
    '#global' => [],
  ];

  $data['views']['logged_in'] = [
    'title' => t('Logged In'),
    'help' => t('Check if user is logged in'),
    'field' => [
      'id' => 'logged_in',
    ],
  ];

  return $data;
}

and then in /mymodule/src/Plugins/views/field/LoggedIn.php I had

<?php

namespace Drupal\mymodule\Plugin\views\field;

use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\ResultRow;
use Drupal\views\ViewExecutable;

/**
 * A handler to provide a field that is completely custom by the administrator.
 *
 * @ingroup views_field_handlers
 *
 * @ViewsField("logged_in")
 */
class LoggedIn extends FieldPluginBase {

    /**
     * {@inheritdoc}
     */
    public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
        parent::init($view, $display, $options);
        $this->field_alias = 'logged_in';
    }

    /**
     * {@inheritdoc}
     */
    public function usesGroupBy() {
        return FALSE;
    }

    /**
     * {@inheritdoc}
     */
    public function query() {
        // Do nothing -- to override the parent query.
    }

    /**
     * {@inheritdoc}
     */
    protected function defineOptions() {
        $options = parent::defineOptions();

        return $options;
    }

    /**
     * {@inheritdoc}
     */
    public function render(ResultRow $values) {

        $logged_in = \Drupal\mymodule\Modules\CurrentUser::isLoggedIn();
        return $logged_in;
    }

}

Some of the contents of LoggedIn.php might not be necessary (not 100% sure) I was using another module as an example.

0

In D7 views supported distinctions between 2 views based on the Permissions/Roles settings per View.

I'm not sure this functionality exists in D8 of using 1 display over another depending on Permission settings of the View.

In D7 and using Display Suite you can set a view_mode different for the 1st or Nth view row returned by Views. It was a submodule of Display Suite. Using something like DS in D8 should to allow you to modify the View Mode of rows in the view result set depending on the rows' special flag value.

  • I'm researching Display Suite but I'm not seeing how DS in D8 could be used to accomplish this task. – Matt Oct 31 '17 at 23:24
0

I see you've already achieved what you needed but I think the easiest way is to copy over the field's tpl template from the views folder, rename it to the name provided under "Information" in the view's settings put it in your theme's folder, and add

global $user; if($user->uid) {

The other option is a bit of views trickery using the "No results behaviour" option in a field's settings. You would have two views with their visibility controlled by blocks / panels / context etc., one for logged in users with no changes, and one for anonymous users where you exclude the body field from display, add the Boolean field for being logged in, click "Treat 0 as empty", and use the replacement pattern to display the body field if empty.

  • This is Drupal 8 not 7. I only have twig templates not tpl's – Matt Nov 1 '17 at 13:40
0

I posted a module for this (link below) based on Matt's answer, but with a change in the way the render function is done:

https://github.com/andileco/logged_in

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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