1

I have a preprocess function that I would like to run against a view, but I can not seem to be able to access the actual results. I have a custom entity called entity1 with two fields, field1 and field2. This function runs, but the value of $value is never set

function template_preprocess_views_view_hook(&$variables) {
  // View options set by user.

  foreach ($variables['view']->result as $id => $result) {
    //Things I've tried:
    $value1 = $result->field_field_field1;
    $value2 = $result->field_field_field1[0]['raw']['value'];
    $value3 = $result->entity1_field_field1;
    $value4 = $result->field1;
    //and many other things
  }
}

The foreach loop does in fact cycle through for the correct number of results.

1

You need the method getValue() from each field to get the field data from row:

$view = $variables['view'];
$values = [];
foreach ($view->result as $row_id => $row) {
  foreach ($view->field as $field_id => $field ) {
    $values[$row_id][$field_id] = $field->getValue($row);
  }
}

If you want the rendered field use $field->render($row)

| improve this answer | |
  • I found that $value = $result[$id]->_entity->field1->value, but your code looks better. – Kevin Nowaczyk Jan 24 '17 at 22:10
  • 1
    That's the field value from the entity, not from the view result. – 4k4 Jan 24 '17 at 22:12
  • Thanks for clarifying. Luckily in my case they are the same, but I can imagine in many cases they would not. – Kevin Nowaczyk Jan 24 '17 at 22:14

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.