1

I'm using Views in 8.4.0 and attempting to change the output of a field value with hook_views_pre_render(). The default value of the field is a node ID. The intent is to replaced the value with a static string depending on a whether or not it's contained in a predefined array using in_array().

The aforementioned is relatively straightforward.

I begin by looping through the results:

  for ($i = 0; $i < count($view->result); $i++) {
    if (isset($view->result[$i]->node_field_data_node__field_lesson_nid)) {
      $viewed = in_array($view->result[$i]->node_field_data_node__field_lesson_nid, $viewed) ? 'yes' : 'no';
      // Replace the default Node ID value with $viewed.
      ...
    }
  }

The array $viewed contains a list of predefined node IDs. If the node ID exists in the array "yes" is output otherwise "no".

The problem is how to output the value for each row of results within the View object.

I tried the following at the above ellipsis:

      $view->field['nid_2']->options['alter']['text'] = $viewed;
      $view->field['nid_2']->options['alter']['alter_text'] = TRUE;

"nid_2" is the token for node_field_data_node__field_lesson_nid.

The problem is this changes the field value for every row. The last row in the results determines the value. (The View also has multiple joins (relationships) which further compounds the complexity.)

So my dilemma is where to replace the value within each row of the $view->result.

Your Answer

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

Browse other questions tagged or ask your own question.