Drupal – Sharing data across fields in the same row with Views Custom Field

We have talked about the Views Custom Field module previously. If you have no idea what is it for, you can take a look @ Drupal – Custom PHP code for Views Field.

Sometimes we may need to get a full node using Views Custom Field. For example, i want to get the number of images of a node.

<?php
  $center = node_load($data->nid, NULL, TRUE);
  if (empty($center->field_center_image[0])) {
    print "0";
  } else {
    print(count($center->field_center_image));
  }
?>

 

Everything works fine. But suppose you want to get the number of another fields, it is definitely not a good approach to reuse the above snippet and load the node again.

The workaround is to temporarily store the next field data in the $data array. Let’s make some changes to the above code snippet.

<?php
  $center = node_load($data->nid, NULL, TRUE);
  if (empty($center->field_center_image[0])) {
    print "0";
  } else {
    print(count($center->field_center_image));
  }

  // Store the number of school images for the next field
  if (empty($center->field_school_image[0])) {
    $data->customfield_school_image_count = 0
  } else {
    $data->customfield_school_image_count = count($center->field_school_image);
  }
?>

 

So now you can add a new custom field and simply print the stored data.

<?php
  print $data->customfield_school_image_count;
?>

 

Done =)

Reference: Cannot reference $static to pass data from one phpcode field to another

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.