Popular just now


Drupal 7 Views: Getting User and Node Reference ID from row using PHP

Drupal views is my default system for creating sites where an administrator or webmaster can configure a website after it has been developed. Unfortunately the community has misled many into believing that anything can be done using Views, Rules and a handful of popular modules without coding. This is definitively not true! And even if you can code it is a dangerous road to walk.

So here's my latest gripe. Connecting User and Node References, counting references and displaying the right information.
If you try to get the node id or user id from a reference it is not available in the $row variable as it should be. Ask the programmer why because I have no idea what this variable is good for otherwise. The output from it is:

stdClass Object
    [field_tutor] => 18
    [field_school] => 7
    [field_school_year] => 18
    [field_student] => 18
    [field_tutor_1] => 18
    [php] => 

Referenced field values are the node id of the parent and not the value that actually connects the information to the node or user content. The information is available though in the $data variable.

print $data->_field_data['nid']['entity']->field_student['und'][0]['nid']; // note nid not "value"
print $data->_field_data['nid']['entity']->field_tutor['und'][0]['uid']; // note uid not "value"

This took me about three days of hunting and frustration (along with a good portion of trial and error) and cost me a deadline. So posting it here might save you the same because there is no straight forward answer about this even from the Fields API creator or the Views team.

No comments:

Post a Comment