2

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);
    }

  }
}
5

Can you please try this code

function my_module_preprocess_views_view_unformatted(&$variables) {

    $view = $variables['view'];

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

        $uid = \Drupal::currentUser()->id();
        $rows = $variables['rows'];
        foreach ($rows as $id => $row) {

            //$owner = $row['content']['uid']['#object']->get('uid')->getString();
            $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);

        }

    }
}
  • 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 '18 at 8:46
  • 2
    Thanks @raj, Thats work like a charm for me :), thanks for your answer. – Udit Rawat Feb 21 '18 at 5:25
  • @Raj Had to change '$view->id()' to '$view->storage->id()' in drupal 8.5 in order for it to work. Thanks! – Stef Van Looveren Jul 16 '18 at 15:39
  • In 8.5, last line need to changed to $variables['rows'][$id]['attributes']['class'][] =$css_class; – Sharique Aug 1 '18 at 13:17

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.