3

I'm using views to show different fields of an entity. If the uid of the entity is the current user I would like to add a custom class to the entire row (not only to the field).

I wrote the following preprocess function that works fine if I use the entity in views, but I don't know how to change it when I use fields instead:

function my_module_preprocess_views_view_unformatted(&$variables) {

  $view = $variables['view'];

  if ($view->id() == 'my_view' && $view->current_display == 'page_1') {

    $rows = $variables['rows'];
    foreach ($rows as $id => $row) {

      $uid = \Drupal::currentUser()->id();

      $owner = $row['content']['uid']['#object']->get('uid')->getString();

      $class = ($uid == $owner) ? 'own' : 'other';

      $custom_row_class = 'views-row-' . $class;
      $variables['rows'][$id]['attributes']->addClass($custom_row_class);
    }

  }
}

1 Answer 1

8

Can you please try the following code snippet. I swapped the line to retrieve the author's user ID.

/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE_preprocess_views_view_unformatted(&$variables) {

  $view = $variables['view'];
  if ($view->id() == 'MY_VIEW' && $view->current_display == 'MY_DISPLAY') {

    $uid = \Drupal::currentUser()->id();

    $rows = $variables['rows'];
    foreach ($rows as $id => $row) {

      // Get user ID.
      $owner = $row['content']['#row']->_entity->get('uid')->target_id;

      $class = ($uid == $owner) ? 'own' : 'other';
      $custom_row_class = 'views-row-' . $class;

      $variables['rows'][$id]['attributes']->addClass($custom_row_class);
    }
  }
}
4
  • thanks, works fine. How can I make it more generic to support both use cases, i.e. how do I evaluate whether the view shows an entity or fields? Unfortunatelly I'm not able to inspect the variables as I always get an error when I try to use kint. Is there a better way?
    – Franz
    Feb 20, 2018 at 8:46
  • 2
    Thanks @raj, Thats work like a charm for me :), thanks for your answer.
    – Udit Rawat
    Feb 21, 2018 at 5:25
  • 1
    @Raj Had to change '$view->id()' to '$view->storage->id()' in drupal 8.5 in order for it to work. Thanks! Jul 16, 2018 at 15:39
  • In 8.5, last line need to changed to $variables['rows'][$id]['attributes']['class'][] =$css_class;
    – Sharique
    Aug 1, 2018 at 13:17

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.