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.

1 Answer 1


I was trying to do something similar as well. I had an integer field and I wanted to replace the integer column with a string value. That was not working. So I had to add a separate string field, maintained the integer field as a hidden field and then overwrote the string field. The code that worked is given below.

function module_views_pre_render(ViewExecutable $view) {
  // Change the comments column in the list of filings table in the view case
  if ($view->id() == 'my_view') {
    foreach ($view->result as $key => $value) {
      $custom_id = $value->_entity->get('custom_id')->value;
      $string = convert_id_to_string_get_user_name($custom_id);
      $value->_entity->set('string_field', $string);

There is documentation and sample snippets here but looks like it needs more documentation.


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.