0

When pre-rendering a view row is there a way to add an HTML class into a single row of the markup, allowing me to add a new background colour to the event item highlighting its importance? This is for the calendar module monthly view

For example,

<div class="row"></div>
<div class="row this-item-was-added-using-view-views_pre_render"></div>
<div class="row"></div>

Below the is the what I have so far.

function pnc_views_overrides_views_pre_render(\Drupal\views\ViewExecutable $view)
{
      if ((int)\Drupal::currentUser()->id() === 1) {
        foreach ($view->result as $key => $value) {
          try {
            $field_result_value = $value->_entity->field_display->getValue();
            if (isset($field_result_value[0]) && (int)$field_result_value[0]['value'] === 1) {
              // add a class to the change the background color to hi-light its importance 
            }
          } catch (Exception $e) {
            \Drupal::logger('viewoveride_pnc_cal_views_overrides')->error($e->getMessage());
          }
        }
      }
}
  • 1
    What do you mean by "inject a class into a single item"? What type of class to you want to inject? – Jdrupal Sep 11 at 7:20
  • I have updated the question thanks – purencool Sep 12 at 0:59
0

Because you do not want to alter some data, you should use a preprocess function for this. Check this out:

function MYMODULE_preprocess_views_view_unformatted(&$variables) {
  $view = $variables["view"];
  $viewId = $view->id();
  if($viewId == 'my_view_id'){
    $rows = $variables['rows'];
    foreach ($rows as $id => $row) {
      $important = $row['content']['#row']->_entity->get('field_result_value')->getString();
      $custom_row_class = 'views-row-' . $important;
      $variables['rows'][$id]['attributes']->addClass($custom_row_class);
    }
  }
}
  • How do I get the current nid of the node that is being rendered in view? – purencool Sep 16 at 21:28
  • @purencool, that would be $row['content']['#row']->_entity->id(); – Stef Van Looveren Sep 17 at 13:13
  • OK, but this does not work on the calendar module and I think that is what is making it confusing. Which is I have not stated anywhere – purencool Sep 17 at 21:48

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.