New Summary

The variable $row should contain the values to be used in views PHP. It does not. $row only gives numbers, which appear to be node ID's.
This issue tries to resolve that.

Workarounds

A list of workarounds that are currently required but would ideally be unnecessary:
- use the variable $data->_field_data instead of $row, like this:

$url = file_create_url($data->_field_data['nid']['entity']->field_image['und'][0]['uri']);
$width = $data->_field_data['nid']['entity']->field_image['und'][0]['width'];
$height = $data->_field_data['nid']['entity']->field_image['und'][0]['height'];

- Try this:

$entities = entity_load('node', array($row->entity_id)); // node, or any other entity type
$entity = $entities[$row->entity_id];
$title = $entity->title;
$width = $entitydata->field_width['und'][0]['value'];

- Or this:

$node = node_load($data->nid);
$width = $node->field_widht[0]['value'];

- Or read this issue:
#1516348: How to call the value of field within a node so that Views PHP can do its magic.

Improvement Wishlist

Everything has room for improvement! This is a list of changes that would definitely improve the experience of using this module:
- a patch in #29, #46, which are combined in #62.


Original Issue

Following is var_dump of $row:
object(stdClass)#367 (12) { ["title"]=> string(24) "Internet connection?????" ["field_review_app"]=> string(3) "313" ["body"]=> string(3) "313" ["field_review_country"]=> string(3) "313" ["field_review_date"]=> string(3) "313" ["timestamp"]=> NULL ["field_review_username"]=> string(3) "313" ["created"]=> string(10) "1303965277" ["field_review_rating"]=> string(3) "313" ["field_review_version"]=> string(3) "313" ["counter"]=> NULL ["php"]=> NULL }

Support from Acquia helps fund testing for Drupal Acquia logo

Comments

zabelc’s picture

I'm seeing the exact same behavior.

It appears that that the fields aren't being dereferenced: the "313" values above refer to the Entity ID being displayed in the row.

RealBirkoff’s picture

Same problem here..

guybedford’s picture

Any news on this issue at all? If any assistance is needed with reproducing, let me know. I could really do with the solution so I can continue to use this amazingly helpful module.

geerlingguy’s picture

Subscribe. Hitting the exact same error. The entity ID (nid, in my case) is being displayed for most of the objects in the row...

rv0’s picture

Same issue as above ruining the fun :(

rv0’s picture

i'm guessing this is a duplicate for

http://drupal.org/node/1061388

meanwhile you can use $data to get to the data.

geerlingguy’s picture

I am unable to get the data from any of the available variables. $data contains the same values for me.

rv0’s picture

try $data in the output field.

and see the other issue, a solution is near http://drupal.org/node/1061388#comment-4642218

guybedford’s picture

Actually, I missed it before, but you can use $data as a temporary fix as mentioned here - http://drupal.org/node/1061388#comment-4473798

geerlingguy’s picture

Using $data instead of the other variables—but only in the output field, as mentioend in #8 above—does work. It's hackish (and against what this module's field descriptions say), but it works.

Hopefully #1061388: Add field data to the result set will get fixed, and resolve this issue as well.

ben kuper’s picture

Same here with a user view, all $row->... returning the user's id.
I have to filter this value so i can't just use the output field, i must use the value code in order to access the right values in the filters.

I could dig a bit deeper in the code if someone has clue on where to start searching. Obviously this is not meant to work like that and there must be somewhere the values are just not assigned.

ben kuper’s picture

Ok, i think the problem resides here : (views_php/plugins/views/views_php_handler_field.inc, line 135)

foreach ($this->view->display_handler->get_handlers('field') as $field => $handler) {
          $normalized_row->$field = isset($row->{$handler->field_alias}) ? $row->{$handler->field_alias} : NULL;
        }

In my case, the $handler->field_alias is always set to "uid" except the username field.
The $field is the correct field's id but i don't really know how to get the correct field's value from that, i looked into the $handler, the $row, the $this and $normalized_row with no success... Maybe the problem comes from another module not return the good field_alias.

Any suggestion ?

ShaneOnABike’s picture

+1 would be great to fix this issue

alexkb’s picture

I think ben kuper (#12) is on the right track. I just did some debugging, and found that the data is in a few different parts in the $values object.. How this data should be accessed is a bit beyond me though.. So for now, the following seems to work:

foreach ($this->view->display_handler->get_handlers('field') as $field => $handler) {
    $normalized_row->$field = isset($values->_field_data[$handler->field_alias]['entity']->{$field}['und'][0]['value']) ? $values->_field_data[$handler->field_alias]['entity']->{$field}['und'][0]['value'] : NULL;
}

or

foreach ($this->view->display_handler->get_handlers('field') as $field => $handler) {
    $key = "field_{$field}";
    $normalized_row->$field = isset($values->{$key}[0]['raw']['value']) ? $values->{$key}[0]['raw']['value'] : NULL;

Think we need someone with some views api v3 experience to help us though, as my hacky attempts above are surely not best practice.

Dan C.’s picture

subscribe

K.MacKenzie’s picture

subscribe

Honza Pobořil’s picture

same issue

timtunbridge’s picture

+1

OnkelTem’s picture

Try adding a field which value you need to the sort.

In my case, for a Node reference field:

BEFORE:

$data->field = <ID of the node of the query> (or 'node' label in $row)

AFTER:

$data->field = <real value of the field>

;-)

orbistertius’s picture

+1

partyp’s picture

subscribe

Honza Pobořil’s picture

Category: support » bug

OnkelTem: Yes, it works, but it is not proper bug fix.

goldlilys’s picture

Subscribing, using both $rows->fields and $data->fields, and they're all spitting out same value for different fields.

afsolano’s picture

subscribe

FAAREIA’s picture

+1

i have drupal 7.8 and views 7.x-3.0-rc1.

I created a user page with views and all the custom fields from the user account returns the user id....using "$row->custom_field".

OnkelTem’s picture

@Bobik

> OnkelTem: Yes, it works, but it is not proper bug fix.

Of course, its not, it is the workaround in some circumstances )

mmilo’s picture

Subscribing... alot of issues for this. Until this is fixed, the module can't function properly.

Marked #1061388: Add field data to the result set, #1188158: Custom Fields Do Not Work As Variables In PHP Filter as duplicates of this issue.

Partially good news in that I think I've found a fix! Update to come...

trgreen17’s picture

+1

I've tried every combination of the fixes above and all I can manage to get returned (when it's not just blank), is the nid or entity.

All I want to do is put one link in the view if the node has been assigned one taxonomy term, and a different link if the node has been assigned a different taxonomy term. And as far as I know, I need this module to do that.

I'm gonna have to rebuild the whole site in D6 if I can't get this to work like it did when it was called "Views Custom Field." I've gotta have PHP in my Views for this site. Fingers crossed... deadline in 13 days. Ugh.

mmilo’s picture

FileSize
3.25 KB

Here's a VERY VERY rough patch.

Basically it seems the $view->result doesn't contain the right information during post_execute, so we have to move the logic to run the PHP code to pre_render. See #1330112: Views Result is returning "node" for field values...

I'm not a big Views3 person, so I really don't know if this is the best way to do things. Also, not all the fields seem to be showing up.

Also this patch only applies to the PHP Filter, and not fields - you'll have to figure out things based on my code to do it for the other handlers.

Hopefully someone more experienced can step in ...

GlitchFreak’s picture

Sub

FAAREIA’s picture

hi trgeen23, i have something that i could not do with this bug at views php, so i ended using a db query from a views php.

i found that node taxonomy relation is within the "taxonomy_index" table. so if you do something like this, it might work.

$taxonomy = db_query("SELECT tid FROM {taxonomy_index} WHERE nid IN ($row->nid)")->fetchField();
echo $taxonomy;

this select the "taxonomy term id" (tid) column from table "taxonomy_index" within the row that has ## (nid number).
then you could do some "if", to print results based on the tid of the node.

hope it helps, tell if it works.

trgreen17’s picture

@ Stakcreativa

Thanks so much for trying to help. I put that in the Output field with the ... in there and it's giving me MySQL errors. I'm not so good with MySQL, but shouldn't I have to put my field name in there somewhere? Also, and I don't know if this matters, but my nodes have several Taxonomy vocabularies and I am trying to pull from a certain one. Wouldn't I have to tell it that too?

Sorry for my newbyness, I usually don't have to dig this deep to get Drupal to do what I want. But I don't mind, it helps me learn!

Tim

FAAREIA’s picture

well, im a newby too.
I think drupal 7.8 views 3 gave me errors too (i was trying to make it work but i could not), but with 7.9, it works. Also, if i use simple ' ' , it gave me error too......i don't know why.....

$taxonomy = db_query("SELECT tid FROM {taxonomy_index} WHERE nid IN ($row->nid)")->fetchField();
echo $taxonomy;

Remember that "$row->nid" is the node id field.

I looked up, and if your node has more than one taxonomy, then the row is repeated with the nid, but with different tid. Look at your tables and you will se what i mean.

Also, "->fetchField()", brings only 1 result. You need "->fetchAll()", but when you echo $taxonomy, you get the word "Array" and i don't know how to echo the hole array inside XD........told you, i'm a newby too.

perhaps you understand more than me, here are some usefull links.
here and here

if you manage to echo an array, please tell me how to, im learning too =D

rv0’s picture

@Stakcreativa

Don't echo arrays
Install devel and use dpm($array);

FAAREIA’s picture

nice rv0 =)

xtrimer’s picture

+1

K.MacKenzie’s picture

rv0,

is there something wrong with using print_r($array_variable); ???

Stakcreativa, I think the function you are looking for is print_r(); its not specific to drupal, its a php function. has made sense of messy situations many a time in different environments for me. Check out the documention on it here: http://php.net/manual/en/function.print-r.php

geerlingguy’s picture

@K.MacKenzie - print_r() (or var_dump()) are both perfectly acceptable ways of inspecting arrays, objects, and variables...

However, if you have devel.module installed you can, among other things, inspect objects, arrays and variables in ways you never thought possible, AND you simply enter dpm($variable_or_array); in your code, or in your View, or on devel's execute PHP page or block, etc., and your mind will be blown. Pretty colors, clickable array levels, amazing stuff :)

I only use print_r() as a crutch. dpm() can do some fun things, and it's quicker than typing out drupal_set_message().

NancyDru’s picture

trgreen17’s picture

@Stakcreativa

Thanks for your post #33! This is the one that helped me figure it out. Whew.

Tim

melissavdh’s picture

I have also got this bug. However I just printed out the content of $data and noticed that each field name is prepended with an extra "field_", so in the Output Code area I have

$accomm_name = $data->field_field_add_item_name[0]['raw']['value'];

and this lets me get the correct value stored in the field "add_item_name" (which is in the database table field_data_field_add_item_name).

Hope this helps.

bjalford’s picture

Tried this as a php filter with no luck.

if ($data->field_field_sex[0]['raw']['value'] == 'Male') {
return TRUE;
}
bjalford’s picture

Tried this as a php filter with no luck.

if ($data->field_field_sex[0]['raw']['value'] == 'Male') {
return TRUE;
}
juamargu’s picture

I have get the value of the field writing in "Output code":

$data->field_field_add_item_name[0]["rendered"]["#title"]

This lets me get the correct value stored in the field "add_item_name" (which is in the database table field_data_field_add_item_name).

I'm using Drupal 7.8.

bjalford’s picture

print $data->field_field_sex[0]["raw"]["value"];

in a PHP field gives me the value, either Male or Female

but when I add a Global PHP filter (without

...)

<?php
if ($data->field_field_sex[0]["raw"]["value"] == "Female") {
return TRUE;
}

I get: Notice: Undefined property: stdClass::$field_field_sex in __lambda_func() (line 1 of /Applications/XAMPP/xamppfiles/htdocs/test/sites/all/modules/contrib/views_php/plugins/views/views_php_handler_filter.inc(82) : runtime-created function).

Any ideas?

mahmost’s picture

Status: Active » Needs review
FileSize
1.27 KB

This is a simple patch to correct the value of $data variable in value PHP code in the field handler only, based on what @mmilo said in #29.
For me, this made $data contains the following :

    [node_title] => Node Title
    [nid] => 21
    [node_created] => 1313872552
    [field_data_field_myfield_node_entity_type] => node
    [views_php_1] => myphpvalue
    [_field_data] => Array
        (
            [nid] => Array
                (
                    [entity_type] => node
                    [entity] => stdClass Object
                        (
                            [vid] => 5
                            [uid] => 1
                            [title] => Node Title
                            [log] => 
                            [status] => 1
                            [comment] => 2
                            [promote] => 0
                            [sticky] => 0
                            [nid] => 21
                            [type] => nodeType
                            [language] => und
                            [created] => 1313872552
                            [changed] => 1313872552
                            [tnid] => 0
                            [translate] => 0
                            [revision_timestamp] => 1313872552
                            [revision_uid] => 1
                            [body] => Array
                                (
                                )
                             [field_myfield] => Array
                                (
                                    [und] => Array
                                        (
                                            [0] => Array
                                                (
                                                    [value] => raw_value
                                                    [format] => 
                                                    [safe_value] => safe_value
                                                )
                                        )
                                )
                            [cid] => 0
                            [last_comment_timestamp] => 1313872552
                            [last_comment_name] => 
                            [last_comment_uid] => 1
                            [comment_count] => 0
                            [name] => admin
                            [picture] => 0
                            [data] => b:0;
                        )
                )
        )
    [field_field_myfield] => Array
        (
            [0] => Array
                (
                    [rendered] => Array
                        (
                            [#markup] => markup_value
                        )
                    [raw] => Array
                        (
                            [value] => raw_value
                            [format] => 
                            [safe_value] => safe_value
                        )
                )
        )

Two important notes about this patch:

  1. The value PHP code will be executed twice, once in post_execute (as it used to be) and another in the pre_render (to correct its value), the only reason for leaving the it in the old position (post_execute) is that click sorting code in post_execute is dependent on the value PHP code.
  2. When the value code is executed at the first time the $data variable is as it is before the patch so it may give a PHP error along with the required result, to avoid the error use an if-statement like this :
    if (isset($data->_field_data)) {
    return $data->field_field_myfield[0]['rendered']['#markup'];
    }
    
arski’s picture

subscribing.. same for me, all $row variables are set to the nid, and the new PHP variables are defined are "NULL" in the subsequent fields.. (If I do "return $somevalue;" in the "Value" field, it's "false"...)

Hope to see a fix committed soon.

trgreen17’s picture

Title: Variables not returning correct values » In case this helps anyone, here's how I solved my issue. Straight PHP/MySQL with no tokens.

Not claiming it's efficient or elegant, but it works. The tokens never did work for me so this is how I solved it.

It shows a certain style of link if an author has one taxonomy term, and another style if they have another. You can see it in action here: healthpolicyforum.org In the center column, notice some of the authors have the words "and the Center" in their link. This code determines that based on the type of author they are. Thanks to Stakcreativa in #33 above, for leading me to the answer.

<?php
$authortype = db_query("SELECT tid FROM {taxonomy_index} WHERE nid IN ($row->nid)")->fetchField();
$nickname = db_query("SELECT field_author_nickname_value FROM {field_data_field_author_nickname} WHERE entity_id IN ($row->nid)")->fetchField();

if ($authortype == 4) {
  echo '<a href="node/';
  echo ($row->nid);
  echo '">';
  echo 'Read more from ';
  echo $nickname;
  echo ' and the Center...</a>';
} else {
 echo '<a href="node/';
  echo ($row->nid);
  echo '">';
  echo 'Read more from ';
  echo $nickname;
  echo '...</a>';
}
?>
geerlingguy’s picture

Title: variables not returning correct values » Variables not returning correct values

(Please leave the title generic, as it's describing the issue in general, and not your comment...).

trgreen17’s picture

Title: In case this helps anyone, here's how I solved my issue. Straight PHP/MySQL with no tokens. » Variables not returning correct values

Huh? I have no idea what you mean.

Oh, I get it... for consistency. It makes it easier for people to track the issue, and they're used to that title while tracking it. Duh.

I see you already changed it back. Cool.

furberd’s picture

I think this is a bug in Views, not Views PHP. For some reason the field_alias property of the view field handler returns "nid" (or "uid" etc) instead of the field name for the handler in question. When that problem is fixed, this module will work properly. Meanwhile, the following will work:

      foreach ($this->view->display_handler->get_handlers('field') as $field => $handler) 
      {
          if (count($handler->aliases) > 0)
          {
              $raw_value = $handler->get_value($values, $field);
              if (is_array($raw_value) && array_key_exists(0, $raw_value))
                $raw_value = $raw_value[0];
              if (is_array($raw_value))
                  $raw_value = array_key_exists('value', $raw_value) ? $raw_value['value'] : null;
              $normalized_row->$field = $raw_value;
          }
      }

Reason not to accept this fix as more than a hack:
When views renders a field, it sanitizes the value. When you access the value directly, it is unsanitized. So use with caution!

jtse’s picture

Subscribe

arski’s picture

@furberd: are the Views people aware of the issue? If so, could you link to it please.

revyd’s picture

New Drupal user and beginner php. Spent the last four hours trying to figure out why the values returned in this field were wrong.

Sorry for the noob question, but @furberd, where do I insert that code snippet?

GlitchFreak’s picture

Hi revyd

You need to install Views PHP and create a PHP field in your view. You can then insert that code in the code field.

Honza Pobořil’s picture

Is this issue going to be fixed? It has been reported in April...

fizk’s picture

Bump

David Vespoli’s picture

subscribe

NancyDru’s picture

johnv’s picture

This patch combines #29 (for handler_filter, handler_pager) and #46 (for handler_field) with no further changes. Still needs testing.
Remember to flush caches after applying this patch!
The patch (posted in #62) contains the following changes:
- $normalized_row->$field = $row->{$handler->field_alias} $row->{'field_'.$field};
- use hook_views_post_execute() hook_views_pre_render()

Also consider #1088776: Views PHP pre and post execute extender implementation

Change the function name php_post_execute() in views_php_handler_field.inc to post_execute() and php_pre_execute() to pre_execute().

That might be a better approach??

liquidcms’s picture

@johnv - patch?

i guess custom sorts don't work either? i tried putting one together yesterday; seemed like a very cool concept to compare $row1 and $row2 and return +1, -1, 0 based on these.. but of course.. $row1 and $row2 have no data.. not completely sure but i think not even nid's for row2 so hard to do any comparison.

johnv’s picture

Oops, here's the promised combines patch.

@liquidcms, based on other issues, sorting doesn't work either. It might benefit from the same changes.

cameron prince’s picture

The patch in #62 is buggy and ineffective for me. There's a broken comment beginning at line 32 of views_php_plugin_pager.inc once the patch is applied which results in: PHP Parse error: syntax error, unexpected ',' and WSOD. After fixing this comment, $row still has id's instead of values.

cameron prince’s picture

I removed the patches and was able to get everything working in my field using variables like this:

$url = file_create_url($data->_field_data['nid']['entity']->field_image['und'][0]['uri']);
$width = $data->_field_data['nid']['entity']->field_image['und'][0]['width'];
$height = $data->_field_data['nid']['entity']->field_image['und'][0]['height'];

itamair’s picture

Brillant cameronbprince!!! It is tricky, but it works ...

revyd’s picture

@cameronbprince Works great except when I try to get taxonomy values. Can't seem to work those out.

drjonez’s picture

:|

charlie-s’s picture

You can always just do

<?php $entity = entity_load('[entity_type]', array($row->id)); ?>

And then access your data directly like

$entity->title

I don't actually think there's a lot of overheard here since entity loads are cached per page load and therefore there shouldn't be extraneous database requests in doing this. Correct me if I'm wrong.

cameron prince’s picture

The bottom line is Drupal is moving away from allowing PHP to be entered in the admin UI... Certainly this is less convenient in a lot of cases, but the reasoning for the change is sound.

I've abandoned the use of Views PHP and wrote custom modules and handlers to perform the tasks I need.

FAAREIA’s picture

mmmmmmmm, what about people that don't know how to write a module?? i think it's vital to use some php when needed.

RdeBoer’s picture

There is certainly a place for this module and it is a shame that work on it seems to have stopped. Let's hope it's temporary.

By the way, the $static variable does not work either.

itamair’s picture

#68 didn't work for me, due the wrong entity id call and that $entity definition that actually returns an array and not an object ...

It should be like this instead:

$entities = entity_load('node', array($row->entity_id));
$entity = $entities[$row->entity_id];
charlie-s’s picture

itamair: [entity-id] is a placeholder where you would insert the name of the entity you're trying to load, such as a field_collection or a taxonomy term or a custom entity. If you're loading a node then you're better off using node_load($row->nid);

MHLut’s picture

I tried to get a field value from a taxonomy term (in this case, a user reference, formated as UID).

The field itself prints right directly from outside the PHP field. However, when hidden and called in my PHP field code, using $row->name_of_the_field, I always get the term ID returned.

I tried different ways of formatting the user reference just in case, but that doesn't change anything.

johnv’s picture

@mhlut, $row does not give useable data. use $data instead, e.g.
$width = $data->_field_data['nid']['entity']->field_image['und'][0]['width'];

neoziox’s picture

I am a French user and I don't understand all the subtleties of this long post. Anyone can tell me if there is a solution (provisional) for this problem?

neoziox’s picture

Issue summary: View changes

Clearer description of issue.

johnv’s picture

Title: Variables not returning correct values » Variable $row does not contain correct values ($data->_field_data does)

@neoziox, I have updated the issue description on top. You can find everything there.

johnv’s picture

Issue summary: View changes

More detailed solutions

johnv’s picture

Marked #1348954 as duplicate:

Posted by egarias on November 24, 2011 at 10:14pm
Ended up with the following:
using entity view in my view with different view_modes.
Then customizing preprocess_node

function mytheme_preprocess_node(&$vars) {
$vars['theme_hook_suggestions'][] = 'node__' . $vars['type'] . '__'.$vars['view_mode'];
}

and Then using the node--node_type--view_mode.tpl.php to theme my output, found this more flexible as I have all the $node available and more flexibility to theming the output.

neoziox’s picture

FileSize
124.58 KB

$myValue = $data->_field_data['nid']['entity']->field_nom_societe['und'][0]['value']; doen't work every time. So you can put this code in the Output area:
print var_export($data, TRUE);
and get the the right elements as you can see in the picture.

In my case, I had this too (as appropriate):
$myValue = $data->_field_data['node_users_nid']['entity']->field_nom_societe['und'][0]['value'];
and sometimes, $row->nid work normally.

And ALWAYS put ALL in the Ouput area.

MHLut’s picture

Guys, don't forget that is not NOT how you should call entity values in D7. In D7, the D6 method has become unwanted, especially because language codes are part of the array. 'und' means undefined language, but it might as well be EN, NL, DE etcetera.

I found a nice blog post about this, that explains it all nice and clearly.

johnv’s picture

So $output = field_view_field('node', $node, 'field_name'); would be a better method.

ressa’s picture

I was struggling with getting the total amount from a Commerce order, but finally succeeded:

// get the total amount from the Commerce order
$entities = entity_load('commerce_order', array($row->commerce_order_total));
$entity = $entities[$row->commerce_order_total];

$total_amount = ($entity->commerce_order_total['und'][0]['amount'] / 100);
print "Total Amount: " . number_format($total_amount, 2, ',', ' ');
fehin’s picture

#31 was the only thing that worked for me. Thanks Stakcreativa!

MHLut’s picture

What is the development status of this issue? It's been over a year since this it was posted and it's affecting a very vital part of this module. If it isn't a top priority yet, please make it one!

nevosa’s picture

managed to get the value of a field_collection_item this way (thanks ressa):
$entities = entity_load('field_collection_item', array($row->field_fg_other_details));
$entity = $entities[$row->field_fg_other_details];
print ($entity->field_fg_other_details['und'][0]['value']) ;

luco’s picture

the way this is set up, it's misleading at best.

if $row->somefield will always return the node ID, then the documentation and interface should change.

IMHO that's a usability issue - a grave one.

rennevat’s picture

This allowed us to pull taxonomy terms:

$data->field_field_year_published[0]['rendered']['#markup']

deggertsen’s picture

Just in case anybody else had this problem.

I couldn't call the nid with $data->nid, but $data->entity did work. I only discovered that I could use $data->entity after putting print_r($data); in my Output code to see what was available. Funny thing is it said $data->nid should be available, but for some reason it wouldn't work for me.

MHLut’s picture

Considering almost every value currently returns an ID (also requested that ID worked for me) you can simple use node_load(), taxonomy_term_load(), user_load() etc. to get the data you want, until this is fixed.

nodecode’s picture

I'm using the advice in #79 and it works for me.

I really wish this issue could be settled, however. Where did the progress on this issue stall? I can't make heads or tails of it. It's hard to believe this module has over 14,000 users and it still hasn't come out of dev.

clevername’s picture

I think it's important to note that the solution in #86 works for View PHP when used as a field, but not in my case when used as a filter. For that see #1 here: #1222448: Views PHP Can't Filter

anicode’s picture

#92 worked for me although not sure how efficient it is. Waiting for the solution.

crystal_alexandre_froger’s picture

I found that $data does not show entity reference fields value:

(Object) stdClass
    nid (String, 5 characters ) 46044
    node_title (String, 59 characters ) Title of my node
    node_language (String, 2 characters ) en
    node_created (String, 10 characters ) 1343188330
    users_node_name (String, 11 characters ) User name
    users_node_uid (String, 3 characters ) 257
    field_data_field_mynode_node_entity_type (String, 4 characters ) node
    field_data_field_myfield_number_node_entity_type (String, 4 characters ) node

The first field of my view is field_mynode which is an entity reference field.

Anyone has the same issue?

Anonymous’s picture

Yes, #88 worked for me using

dsm($data);

to target the field and value.

S

Vote_Sizing_Steve’s picture

I found that the fields were available (not just as node ids) once I went to the field edit page and checked the:

[ ] Expose as base table
Expose the storage table for this field to the Views module as a base table.

... setting at the bottom of the form.

El Bandito’s picture

@Vote_Sizing_Steve

Where are these options ? Can you provide an example URL to the edit page as I've no recollection of ever seeing them before.

Thanks.

geerlingguy’s picture

@Vote_Sizing_Steve - it looks like those options are only available for those using the Views Field module, which wouldn't help with most people's difficulties.

El Bandito’s picture

Maintainers

This is SUCH a useful module and 99 posts on this issue does indicate that there is much anticiptation for a fix on this one.

What kind of compliments are required to motivate you clever people ? Unfortunately cash isn't an option :<

El B

linus79’s picture

subscribe

mshepherd’s picture

@linus79
no need to subscribe like this anymore. just click the follow button at the top of the post.

richH’s picture

Hi,

I want to make a birthday list which is sorted by the month/day of the birthday and doesn't use the birth year. Ideally I want dates/views modules to handle this but they don't so I tried this module which has turned out to be a real pain because

1) the $row variable only return the node-ID in the birthday field and

2) the numeric sort doesn't work because the function name isn't a string.

All these problems are reported in the issues list.

I posted my problem under #1785740: Sort a view on month and day only (for birthday list) which turns out to be duplicate of this node. I have just been through all the posts here and managed to get a solution to my problem which I've posted here under comment #4 on my post.

Hope this helps everyone but to be honest these bugs really need to be fixed to make this module usable. The whole point of drupal is that I don't have to code and read the php.net manual which I had to do here.

all the best and thanks for all the tips
Rich

MasterChief’s picture

This bug it's a pain, i hope it will be fix soon :)

IWasBornToWin’s picture

Status: Needs review » Active

Yes it is a pain, I just paid for custom php code in my filter (my php skill lack) only to learn it not only doesn't work for $row or $data, it wont even work for db_query. Is there a page of any sample code that WILL work for this module? A lot of people use it so I assume they're either drupal 6 or i'm missing something for 7?

luco’s picture

@richH & @IWasBornToWin, I've recently coded a small monthly archive in a website.

the following code assumes your view has two arguments, year and month. take a look and see if you can fiddle with it.

note: you have to fill in Setup code and Output code. don't forget opening and closing PHP tags in Output code and leave Value code empty!

Setup code (first field of Global: PHP)

if(is_null($static)){
    $static = array();
}
$static[0] = $static[1] = "";

Output code (third field of Global: PHP)

<?php

$newyear = date('Y', $data->node_created);
$newmonth = date('m', $data->node_created);

if ($static[1] != $newyear) {
  echo "<a class='blog-year' href='" . base_path() . "blog/" . $newyear . "'>" . $newyear . "</a>";
  $static[1] = $newyear;
}
if ($static[0] != $newmonth) {
  echo "<a class='blog-month' href='" . base_path() . "blog/" . $newyear . "/" . $newmonth . "'>" . $newmonth . "</a>";
  $static[0] = $newmonth;
}

?>

this code is pretty clumsy, but got the job done. :S

agileadam’s picture

I was able to get what I needed by using PHP in the "Output code" field.
e.g.,

if (count($data->field_field_gender) == 2) {
  print 'Unisex';
}
else {
  print $data->field_field_gender[0]['rendered']['#markup'];
}
Bartezz’s picture

Encounterd the same bug, big pain in the... and I can't seem to find the solution when I look at the code!

gnal’s picture

Same for me here, trying to add a php filter.
The only workaround that worked is to load the node object with node_load() and then getting the fields with field_get_items()... but the performance will be terrible for a lot of results, so only using it as a temporary workaround.
This bug has 107 replies, there doesn't seem to be a fix close and in many cases it makes the module completely unusable. Shouldn't there be a warning in the description page?

Ironwill’s picture

Hi all,
Sorry if my format is wrong, I'm still new at this!

For the life of me, I can't manage to get this module to reference my display price from ubercart (calculated through uc_custom_price). I have one column using the standard handler in Views to show the display price which works fine, but I would like to add another one which I can calculate a new formula (eg. display_price * 3)

Up till now i have tried to install the patches, used $data->field_display_price as well as the other suggestions on this page. I have also tried to replace "display_price" with custom_code but unfortuantly had no success.

I would be extremely grateful for any help/tips/solutions you may share. Thanks in advance!

Ironwill’s picture

Ok so I managed to find a different route to make this happen.

Instead of calling the display price through Views PHP, I created a duplicate display price field (using given handler) and hid it from view, then used Global Math Expression to calculate a formula on this. There was difficulty due to math not allowing strings, but changing the formatter from ubercart to numeric solved this for me.

I hope that this may help others who were in my situation.

Bartezz’s picture

No news?

dankoB’s picture

@Ironwill. Try $data->field_field_display_price[0]['raw']['value'] in the output code. I don't understand why the need for field_field, but this is what has worked for me as a workaround for several PHP fields in Views. Don't forget to have a line to print your output variable. Hopefully the bugs will be resolved eventually and we can use the variables listed as available and the Value code too so we can click to sort. Incidentally, this method works for getting data to the PHP field, but not for PHP filter. No workaround for that one yet as far as I know.

javier.drupal.2012’s picture

Hi all,

I'm struggling trying to find a solution. I want to use a dynamic field (Proximity: distance from openlayers proximity) in my php code. I can access to the node fields using $data->field_field_display_price[0]['raw']['value'], however, I don't know how to access to the proximity: distance field.

I try to use print_r($data) to check the structure but this function is not working for me.

Any idea to solve this issue?

Thanks
Javier

johnv’s picture

@javier, install devel module, and try 'dpm($data->field_field_display_price);'

javier.drupal.2012’s picture

Hey @johnv , thanks for your quick answer. It is very odd. I have used dpm($data); and I can see the whole structure and every field. The problem is that I cann't see the dynamic field Proximity: Distance. Maybe I have not been clear enough.

The dynamic field proximity: distance is a field, which is generated when the view is being processed. This field doesn't belong to the entity. The proximity field is worked out like the distance between a node geofield point and a paramater.

Reading the available variables in the PHP Views, one variable is $row->field_display_price and other one is $row->distance. I would like to be able to read the $row->distance.

Any idea?

Thanks

-------------UPDATE-------------------------------

It is working fine, well, I kind of fine.

For fields which belong to the entity the best way to access them is using $data->field_field_display_price[0]['raw']['value']
For dynamic fields it is possible to access them using the available variables provided by Views PHP module (eg. $row->distance)

Thanks

vgutekunst’s picture

#106 worked for me with drupal 7. THANK U VERY MUCH!

but:

print $data->field_field_gender[0]['rendered']['#markup'];

dont work for me for the fields "path" and "view_node" any help for that? I want to outpout the field "content:path" with global php.

monaw’s picture

The "Output code" field is not available when you use the the PHP in filter (see attached image) and so $row and $data are not giving me the info for my CCK fields; here is what I get:

row : stdClass Object
(
[nid] => 21
[title] => 519abad2a18b05.34579239
[field_user_data_access] =>
[field_user_data_access_users] =>
[field_user_data_size] => 21
[field_user_data_files] => 21
[field_user_data_plot_files] => 21
[field_user_data_image_sequences] => 21
[field_user_data_movie_files] => 21
[name] => bob
[timestamp] => 1369094865
[edit_node] => 21
)
data : stdClass Object
(
[nid] => 21
[node_title] => 519abad2a18b05.34579239
[users_node_name] => bob
[users_node_uid] => 2
[node_revision_timestamp] => 1369094865
[field_data_field_user_data_size_node_entity_type] => node
[field_data_field_user_data_files_node_entity_type] => node
[field_data_field_user_data_plot_files_node_entity_type] => node
[field_data_field_user_data_image_sequences_node_entity_type] => node
[field_data_field_user_data_movie_files_node_entity_type] => node
)

For now, I have to do a node_load ($row->nid), this is a huge performance hit as it must be done for each node (again)!

PLEASE FIX!

richH’s picture

Hi,

have I missed something? This post has (luckily) turned into a 'how do I work around this bug' discussion but the problem still isn't being fixed. We're all frantically trying to find work arounds etc because the variables don't contain the right data.

Is this correct - I haven't kept really up to date on the postings, but I get the feeling that this is considered solved because we're all finding solutions to our problems

Cheers
Rich

gianfrasoft’s picture

@richH, I agree. I also think that a new version of this module will make all of these workaround unnecessary and self-defeating by blowing each of them.

fizk’s picture

@gianfrasoft, I also agree. The project's maintenance status is "seeking new maintainers". The last commit to 7.x was over a year ago, and over two years ago for 6.x, so I don't think this module is being maintained anymore.

I've asked to co-maintain the project here: #2001900: Offering to co-maintain Views PHP. If anyone would like to maintain this module, please send an email to the current maintainers, and create a new issue in the issue queue.

Anonymous’s picture

FileSize
186.32 KB

Just agreeing with others that this module is unusable as it stands. Here is some dpm debugging output, which should be self-explanatory.

debugging output

monaw’s picture

Ok, it looks like the $data->_field_data does contain the entire node structure and $data->field_my_cck_field does have the field information ONLY if you render the field. I have a field in the view but when I checked the "Exclude from display", those information in the $data went away!

I need to be able to have the field information if I don't display the field becase my PHP code is actually using it to do some processing.

monaw’s picture

Ok, something weird is going on...I unchecked "Exclude from display" and now the $data->_field_data and $data->field_my_cck_field are still gone! They were there before but no more...weird...now I'm back to basically a useless $data:

data : stdClass Object
(
    [field_data_field_log_result_field_log_result_value] => 1
    [field_data_field_log_type_field_log_type_value] => 5
    [nid] => 101
    [field_data_field_log_result_node_entity_type] => node
    [field_data_field_log_type_node_entity_type] => node
    [field_data_field_log_type_field_log_type_value_1] => 85
    [field_data_field_log_type_delta] => 85
    [field_data_field_log_type_language] => 85
    [field_data_field_log_type_bundle] => 85
    [field_data_field_log_duration_node_entity_type] => node
    [field_data_field_log_duration_field_log_duration_value] => 162
)
liquidcms’s picture

Priority: Critical » Normal

its funny how off topic and long this thread has gotten; but i'll chirp in just to make it worse.. or possibly to bring it back on track.. and maybe we can close this.

first - hardly a critical issue as the module more or less works as designed; it is just a little harder to get at the info you are looking for than the module settings help suggests (here in lies the real issue)

second - the only REAL issue here is (as was originally reported but lost along the way) that $row->field_name does not hold the data that the module help suggests (but it is there buried in $data). i believe the explanation for this has something to do with Views itself and is not fixable by this module.

third - the only REAL bug worth mentioning here is that the help text provided with the settings for this are wrong (actually VERY wrong and quite misleading; hence the length of this thread). we should remove the parts about $row (which has never worked and very sadly unlikely ever will) and add some documentation on the work-around which is something like this:

$data->field_[field_name][0]['rendered']['#markup']

the real killer in all of this is the inability to use the real rendered fields as defined earlier in the view fields list. so always a PITA to add in your img styling, rewritten fields, etc even though it was added to the field above; as that information is not available to this module.

lcampanis’s picture

Priority: Normal » Critical

This bug is just wrong! The simplest workaround I found is to do a node_load($data->nid) and access any fields needed through there. The nid is only field that is correctly returned. So let's use it wisely.

So in short:

In the Value field of the PHP field add:

$node= node_load($data->nid);
return $node->your_field_value;

That should sort it out for most of us, but this needs to be fixed. I assume that views is now returning it's data some other way, and PHP Views needs to rectify that.

FAAREIA’s picture

please do not post anything unusefull at this issue.
lcampanis, what you just post told me that you didn't read the whole issue. Your work-arround it's not the best.

lcampanis’s picture

Would it be possible to give us the best workaround please?
At least until the bug is fixed.

liquidcms’s picture

yes, doing a node load on each nid is far from ideal.

RdeBoer’s picture

Ok... Having gone through most of this and having just released a first cut of Views Aggregator Plus, which has support for VIews PHP, here's my 2 cents worth...
I agree with liquidcms (#124) that the module is in ok condition, just the help panels are misleading, in their current state as they promise information in places where it isn't.

  • to keep it simple I'm using the current 7.x-1.x-dev release (21-Fed-2012) out of the box, no patches
  • I'm putting all PHP in the Output code field, I do not use Value code, as it does not have all data available and I don't want to resort to re-loading nodes (#125) whose info is readily available in the "Output code" field , both raw and rendered -- you just have to know the syntax to use; examples below
  • the price you pay is that column sorting doesn't work. If you want sorting to work with "Output code", enable Views Aggregator Plus; it will sort a Views PHP column "naturally" (numbers and strings), so provided you don't put, say, dollar signs in front of your numbers, it'll work
  • You can use _field_data[...] for raw results, but I prefer the shorter format also available at the same time in the Output code which looks like field_field_... format. For example compare:
    $data->_field_data['nid']['entity']->field_duration['und'][0]['value']
    against the equivalent
    $data->field_field_duration[0]['raw']['value']

Here are some examples of the syntax to use for various field types to access them in the Output code textarea. Note that to display these values you need to put "echo" in front of the expression. And use the <?php and ?> "brackets" around everything.

// General fields, say a field named "Total", machine name: "field_total"
Raw value (for use in calculations): $data->field_field_total[0]['raw']['value'] // 1000
Rendered value (i.e. marked-up for display): $data->field_field_total[0]['rendered']['#markup'] // $ 1,000.00

// Dates, say a field named "Duration" (collecting start & end dates), machine name "field_duration"
Raw: $data->field_field_duration[0]['raw']['value'] // 2013-06-02 00:00:00
Raw: $data->field_field_duration[0]['raw']['value2'] // 2013-06-04 00:00:00
Rendered: $data->field_field_duration[0]['rendered']['#markup'];// "Sun 02-Jun-2013 to Wed 04-Jun-2013"

// Taxonomy terms, say a field named "Industry", machine name: "field_industry"
Raw: $data->field_field_industry[0]['raw']['tid']
Rendered: $data->field_field_industry[0]['rendered']['#title']

Here's an example of a PHP snippet that outputs whether an event is in progress, finished or hasn't started yet.
It assumes that the event contenty type contains a field_duration with start and end dates:

  $start_date = strtotime($data->field_field_duration[0]['raw']['value']);
  $end_date   = strtotime($data->field_field_duration[0]['raw']['value2']); 
  echo time () < $start_date ? 'not started' : (time() < $end_date ? 'in progress' : 'closed'); 
leymannx’s picture

$row->path shows NULL.

Workaround:

drupal_lookup_path('alias',"node/".$data->nid)

FAAREIA’s picture

drupal_lookup_path
Third parameter is language.

Optional language code to search the path with. Defaults to the page language. If there's no path defined for that language it will search paths without language.

interdruper’s picture

Thanks a lot RdeBoer for your illuminating summary info ( #129 ) about this ancient issue.
Only just needed the nomination of a brand new maintainer for this good old orphan module...

ChrisValentine’s picture

Techincally you shouldn't output a field until you know it contains something - test it first, eg:

$instNode = $data->_field_data['nid']['entity'];

$city = isset($instNode->field_institution_location['und'][0]['value']) ? $instNode->field_institution_location['und'][0]['value'] : "not set";
echo "<p><strong>".t("City: ")."</strong>".$city."</p>";
Goofy2k2’s picture

subscribe

prakashsharmapartner’s picture

Hi,

I have used
$content_g = views_get_view_result(new_related_post_content, block_1); $nid = ($content_g[0]->nid);$node = node_load($nid);
in my views .tpl file and this is providing me the proper array for $node.

prakashsharmapartner’s picture

Issue summary: View changes

added reference to 1516348

Goofy2k2’s picture

Subscribe

seanr’s picture

This doesn't work for me at all in a sort - $data->_field_data is empty. $data is not set at all, and $row just outputs the node ID for all of the fields.

seanr’s picture

Accidental double post (d.o is acting up).

spencerthayer’s picture

I have attempted every method mentioned in this post (and others) to get the correct values from a Views Global PHP column. The example code below lists all four major methods for pulling the data and only attempt THREE works for me.

    print "<p>ONE: ".$data->field_description[0]['raw']['value']."</p>";
    print "<p>TWO: ".$data->field_description[0]['rendered']['#markup']."</p>";
    print "<p>THREE: ".$data->_field_data['nid']['entity']->field_description['und'][0]['value']."</p>";
    print "<p> FOUR: ";
        $node= node_load($data->nid);
        return $node->field_description;
    print "</p>"; 

I find it unfortunate that only method three works since it is so damn ugly and akward. Below is another code example with a working example of method three; while it DOES work it is cumbersome and impossible to work with in a practical enviroment.

    // TIME STAMP 1
    $start0 = strtotime($data->_field_data['nid']['entity']->field_time['und'][0]['value']);
    $end0 = strtotime($data->_field_data['nid']['entity']->field_time['und'][0]['value2']);
    // TIME STAMP 2
    $start1 = strtotime($data->_field_data['nid']['entity']->field_time['und'][1]['value']);
    $end1 = strtotime($data->_field_data['nid']['entity']->field_time['und'][1]['value2']);
    // TIME STAMP 3
    $start2 = strtotime($data->_field_data['nid']['entity']->field_time['und'][2]['value']);
    $end2 = strtotime($data->_field_data['nid']['entity']->field_time['und'][2]['value2']);
    // TIME STAMP 4
    $start3 = strtotime($data->_field_data['nid']['entity']->field_time['und'][3]['value']);
    $end3 = strtotime($data->_field_data['nid']['entity']->field_time['und'][3]['value2']);
    // TIME STAMP 5
    $start4 = strtotime($data->_field_data['nid']['entity']->field_time['und'][4]['value']);
    $end4 = strtotime($data->_field_data['nid']['entity']->field_time['und'][4]['value2']);
    // CALCULATION
    $totalMin = (($end0-$start0)+($end1-$start1)+($end2-$start2)+($end3-$start3)+($end4-$start4))/60;
    // RUNTIME
    print $totalMin." min";
    print "<hr style='margin:0;' />";
    $hours = floor($totalMin / 60);
    $minutes = $totalMin % 60;
    if ($minutes < 10) { $minutes = '0' . $minutes; }
    print $hours.":".$minutes." hrs";

I am taking the datetime 'field_time' field, getting the start and end time out with 'value' and 'value2' and then calculating the difference, after that I am adding each 'field_time' entries into a total. The problem I have is that it is very clumsy when trying to deal with these two types of multiple values per field. There are scenarios where I would like to use more than just five time stamps but I don't want to run a new line of code for each new value.

What options exist here? What is the solution to these kinds of problems?

Thank you.

John Pitcairn’s picture

The solution is DRY (Don't Repeat Yourself). You have an array of time values, loop over it:

  $seconds = 0;
  foreach ($data->_field_data['nid']['entity']->field_time[LANGUAGE_NONE] as $time) {
    $seconds += strtotime($time['value']) - strtotime($time['value2']);
  }
  $minutes = $seconds / 60;

johnv’s picture

@seanr, this module has problems with sort/filter/field/argument . Each of them has issues in the issue queue.
IMO this issue indeed only works for 'field'. It is not explicitly stated in this issue, because most people only use 'field data' (i've used field and filter) and are not aware of the other problems. Perhaps if you apply a 'sort' patch, the data becomes magically available,of fixes the problem in another way.

szy’s picture

Guys, how should I print body value?

print $data->body['und'][0]['value']; doesn't print anything - that's taken from print_r ($data).

Thanks,
Szy.

castawaybcn’s picture

I have a similar problem, szy. Did you find a solution?
In my case I can get the value of a field in a certain language with a block conatingin this php code:

<?php
$node = node_load(arg(1));
print $node->title_field['es'][0]['value'];
?>

And I thought I could get the same value to show up in views_php, but I can't figure out how, none of these seem to work:

return $row->[es]title;
print $data->title_field['es'][0]['value'];
print $row->title_field['es'][0]['value'];
print $data->_field_data['nid']['entity']->title_field['es'][0]['value'];
szy’s picture

Nope, I still have this problem too.

Szy.

RdeBoer’s picture

Have another read of #129 in this thread....

castawaybcn’s picture

szy, I guess the code you are looking for is:

print $data->field_body[0]['raw']['value'];

RdeBoer, thanks. I have, but in your examples there is no language variable. I have tried the long equivalent for the above code as you described it:

print $data->_field_data['nid']['entity']->field_body['und'][0]['value'];

Which sadly does not work. I am probably missing something and would appreciate any ideas. The structure of the field I want to output from var_export is the following (trimmed):
'title_field' => array ( 'en' => array ( 0 => array ( 'value' => 'Term node 1', 'format' => NULL, 'safe_value' => 'Term node 1', ), ), 'es' => array ( 0 => array ( 'value' => 'Término 1', 'format' => NULL, 'safe_value' => 'Término 1', ), )

sprice’s picture

@castawaybcn --

In the output, it shows that there is no 'und' for you, so you're calling a non-existent variable. You'll have to pick a language. Basically, you'd have to do something like:
print $data->_field_data['nid']['entity']->title_field['es'][0]['value'];
If you're looking to make the code available for either English or Spanish, then you'll have to grab the user's language first and then use that as a variable... i.e.:

$LANG = do_something_to_grab_the_current_lang();
print $data->_field_data['nid']['entity']->title_field[$LANG][0]['value'];
castawaybcn’s picture

@sprice
Strangely enough I used the exact same code you suggest before (see #143) and didn't work, I tried now and it does. I must have been doing something wrong. Thanks a million!

Edit: I found what the problem was: oddly you need to add the body field in the view, otherwise the title code will not work. A bug perhaps?

lquessenberry’s picture

Will this ever be fixed? It is too time consuming and confusing to see all the $row->blah variables there but don't work for anything. It's about as fun as having a car with an air conditioner that doesn't work. I'd rather have no AC than one that doesn't work. I am about to bash my skull in trying to write filters.

fizk’s picture

Issue summary: View changes

Hi everyone,

I obtained write access to this project so I could fix this issue. Before I got started, it seemed people were saying the code is fine, the problem is we don't know how to use the module properly. Because of this, I decided not to modify the code.

Three years after this issue was created, it seems people are still bumping into walls. That seems to mean that something could be improved - whether it's the code, the instructions, or both.

I think we should update this issue's summary to better understand what improvements should be made.

Please contribute to the "Workarounds" and "Improvement Wishlist" sections in the new summary at the top of this page.

fizk’s picture

Issue summary: View changes
MustangGB’s picture

Who is saying it's working fine?

The problem is not that of lacking documentation, it is that it's not working as desired in code.

Workarounds are only that... workarounds.

MustangGB’s picture

Status: Active » Needs review
FileSize
893 bytes

So here's a potential fix.

johnv’s picture

Issue summary: View changes

Updated the summary (moved existing work-arounds to new section.).
Does the patch in #153 consider the patch from #62?

I'm glad we have a new maintainer! Good luck. A lot of patches already exist in the issue queue. In the past I tried to group them in filter/field/sort/etc handlers. I did not succeed. Each handler has its own problems.

ofry’s picture

Status: Needs review » Reviewed & tested by the community

Patch #153 fixing bug with $row variable. Thank you.

jcam88’s picture

Just applied the #153 patch, looks like its working.

A few log messages. Not sure if this is caused by the patch.

Notice: Undefined offset: 0 in views_php_handler_field->render() (line 213 of .../views_php/plugins/views/views_php_handler_field.inc).

Warning: Invalid argument supplied for foreach() in views_php_handler_field->render() (line 213 of .../public_html/sites/all/modules/views_php/plugins/views/views_php_handler_field.inc).

Notice: Undefined variable: node in __lambda_func() (line 1 of .../public_html/sites/all/modules/views_php/plugins/views/views_php_handler_field.inc(202) : runtime-created function).

Notice: Trying to get property of non-object in __lambda_func() .../public_html/sites/all/modules/views_php/plugins/views/views_php_handler_field.inc(202) : runtime-created function).

Output code: (rewrote a search api indexed image file name field and used the row variable)

<?php
$img_url = $row->field_tag_field_tag_logo_file_name;
$style = 'logo_small';
?>
<img src="<?php print image_style_url($style, $img_url) ?>”>
DiversiCon’s picture

Patch #153 works for me when used in the "Output code". "Value code" still shows null values in $row.

soraver’s picture

Same as #157
At least I can use the feature now :)
Thanks!

  • Commit 4bcee06 on 7.x-1.x by fizk:
    #1140896 akamustang, fizk: Fix $row in "Output code" to show rendered...
fizk’s picture

Status: Reviewed & tested by the community » Fixed

Thanks everyone! I've committed #153, along with a documentation change:

I saw #62, which moves the post_execute() code into a pre_render() so we can see field values, but the trade-off is, in the views hierarchy of events, data is expected to gathered in the execute() step and made available to modules that implement the views_post_execute() hook, as mentioned in the documentation.

guy_schneerson’s picture

Sorry if I am missing something impotent but I don't get why the $row and $data where completely removed.
The php_post_execute() calls the execute function once per a row but dosen't pass in any row information, not even the nid. How can I do row level code without any row data?

fizk’s picture

If you need row level data, you can use the Output code field. Are you seeing any issues doing it this way?

guy_schneerson’s picture

Hi fizk and thanks for responding so quickly :)
Yes I got existing views that use the execute code to build a result that is row specific while building up the $static holding totals for all rows. The output code uses both the $value and the $static to work out averages.

But in any case removing any row data from the execute makes it unusable for any row value calculations. If the entities are not loaded at this point we should at list provide the nid so data can be loaded if needed by the PHP code.

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.

  • Commit 4bcee06 on 7.x-1.x, 7.x-2.x by fizk:
    #1140896 akamustang, fizk: Fix $row in "Output code" to show rendered...

  • Commit 843c5e2 on 7.x-1.x by fizk:
    Revert "#1140896 akamustang, fizk: Fix $row in "Output code" to show...
fizk’s picture

Status: Closed (fixed) » Needs review
FileSize
4.02 KB

@guy_schneerson Sorry for the delay. You made a good point, which caused me to go back and forth on how to properly fix this :)

I'm attaching a new patch against the latest dev. Please test it and let me know what you think. You'll be able to load entities in the Value code, but you'll need to add the "Content: Nid" field to your view to get the nid value. Fields that don't contain data are not shown in the Value code help text, and removed from the $row object.

Seeing that 43,000+ sites are using this module, I think it'll be risky to commit the fix for this issue in 7.x-1.x. I've removed the previous commit from 7.x-1.x and moved it to a new 7.x-2.x branch. All further commits for this fix will go into 7.x-2.x.

fizk’s picture

Status: Needs review » Fixed

Committed #167.

lquessenberry’s picture

Thanks for all the hard work!

  • Commit 4a1d60d on 7.x-2.x by fizk:
    #1140896: Fields that don't contain data are not shown in the Value code...
antoinetooley’s picture

has anyone managed to get the php filter to work with variable added to the data object? I have some pretty complex php to create some custom fields in my view but I would love to filter by these results I generate which I add to the $data object. Does anyone know if this possible? the new dev version doesn't seem to make any difference.
Thanks!

fizk’s picture

antoinetooley’s picture

brilliant! If I can help in any mostly noob way then let me know. Il follow that issue for now though.
Cheers!

sause’s picture

I got a weird work around by adding the field you want to *Sort Criteria", then $data will contain its value.

stdClass Object
(
    [node_title] => Testing
    [nid] => 111
<strong>    [field_data_xxa_field_xxa_tid] => 22</strong>
<strong>    [field_data_field_xxb_field_xxb_tid] => 22</strong>
    [field_data_field_document_type_node_entity_type] => node
    [field_data_field_document_node_entity_type] => node
)
Ariakan’s picture

I have an issue to report.

I have a date field (with both start and end date) where I choose to only show the end date in my view.
If I do echo $row->field_date_name; , it shows me the start date instead of the other one.

fizk’s picture

Ariakan, using the latest dev, I'm able to get the end date using $row->field_date_value2 in the Value code section.

dan.mantyla’s picture

To get the taxonomy name from the taxonomy field for a node in the view:

$data->field_field_my_taxonomy_field_name[0]['raw']['taxonomy_term']->name;

Sadly this is only working as a php field in FIELDS and not FILTER CRITERIA

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.

dev.paulson’s picture

subscribing.

dev.paulson’s picture

Status: Closed (fixed) » Active
dev.paulson’s picture

$data->_field_data returns nothing in filter criteria section. it works only in display Fields.
All other fields returns nid or entity_id.
THIS MODULE IS NOT USEFUL AT ALL NOW.

guy_schneerson’s picture

Hi @dev.paulson
Thanks for the feedback just a few tips to help you become an even more productive part of the community:
1) You don't need to add a "subscribing" comment, just click the "follow" button at the top right of the issue.
2) Remember that both core an contrib modules are developed by people for the love of the platform and they deserve no less than getting some love back. so it helps to be polite and positive in your feedback.
3) I find this module incredibly useful and no issues I have encountered has changed my mind. I find the maintainers incredibly responsive and again remember they are volunteering their own time to do this.

And finally: The more eyes we have the more issues we can identify and fix so I sincerely hope to see more of your feedback in the future :)

jay.lee.bio’s picture

Fizk, I almost overlooked #167, which got the variable $row to finally work for me. Here's a blog post for the newbies: http://jayl.ee/blog/2014/10/29/how-to-use-the-views-php-drupal-module

jay.lee.bio’s picture

Version: 7.x-1.x-dev » 7.x-2.x-dev
Status: Active » Needs review
gianfrasoft’s picture

It seems that patch doesn't solve same problem on views over commerce products...

liquidcms’s picture

very cool.. just tried this out and it seems to certainly be a step in the right direction. i am a little hesitant to use it on an existing site as i am unclear if it expects to break some things; but for new sites; certainly the way to go.

one thing i noticed, i just raised this issue: #2423643: anonymous does not have same $data as authenticated regarding anon access to blocked user data. that issue still applies with this fix.

macdev_drupal’s picture

Just updated to the latest dev of views views-7.x-3.x-dev
It seems like $row isn't working again. The stable views-7.x-3.10 show the same issue.
Did the patch not make it into the 7.x-3.x ???

Update:
Patched the wrong module. Works fine now! Sorry! :-)

jay.lee.bio’s picture

Macdev_drupal, there is no 7.x-3.x. I'm using it on 7.x-2.x with Views 7.x-3.10 and it's working fine for me at the moment.

doitDave’s picture

Four years and, of all things, an issue directly related to the core functionality of a module resides in the recent release?

Also: Confirmed, getting the NID as a value for any $row property in an aggregated view on node entities. Not sure if switching back to global math or just forking...

Pity; such an important views addon. Wow.

No offense, we all lack time for our voluntary babies here, but wtf. :-(

RdeBoer’s picture

Re: #189:

As a maintainer (of other modules), and as a "consumer" (of this one), I can relate to what @doitDave says.

This is a wonderful module.

Despite it not having an official full release, it has a huge user-base (70,000+).

But the module isn't getting the love it deserves.

Why?

There could be many legitimate reasons for it and this is probably not the place to speculate about those.

But it does make one wonder about the way Drupal and perhaps Open Source in general, works and in what aspects it does not work.

fizk’s picture

Status: Needs review » Closed (fixed)

I'll try to work on the filtering bug over the weekend in #1222448: Views PHP Can't Filter.

Please note, the fix for this issue is in the 7.x-2.x branch, and the fix for #1222448: Views PHP Can't Filter will be going to the 7.x-2.x branch.

fizk’s picture

lunk rat’s picture

7.x-2.x-dev solves this issue. Thank you fizk for your contributions!

RdeBoer’s picture

Brilliant fizk! Thanks so much for finding the time.

Anonymous’s picture

Stumbled across this issue with the dev version. When I use $row->type using alpha1 that renders my content type, e.g. blog_post. However when I do the same thing with dev version I get whatever the 'name' for that type is set to, e.g. Blog Post.

Not sure if I'm doing something wrong.

liquidcms’s picture

this is an interesting patch which doesn't exactly fix this issue but may be of some use to those struggling here: https://www.drupal.org/node/1452918#comment-10148292

basically it allows use of the replacement tokens in the php code, so i can use code in a php field like this:

$tid =  '[field_primary_division-tid]';
$term = taxonomy_term_load($tid);
echo $term->field_site_acronym['und'][0]['value'];
liquidcms’s picture

hmm.. no, i think my patch is wrong.. it may only pull token from first row.. ughh

drupal-son’s picture

Hi,

I came here because the $row->field_name issue with value content.
I updated the module so now I'm using views_php-7.x-2.x-dev version.
Not applied any other patch, just the latest 2.x-dev branch.
That fixed the value issue, so now printing something like $row->field_name prints the correct value.

However, I noticed it breaks tokens and other Global PHP field from other fields.
For instance:

1. I have a hidden Global PHP field with: "print $row->title;"
2. I have a Global Custom text field with: "The title is [php]"

That [php] token field came empty.

Another use case:

1. I have a hidden Global PHP field with: "print $row->title;"
2. I have a Global PHP field with: "print 'The title is '.$row->php;

That $row->php variable came empty.

Using views_php-7.x-1.0-alpha3 was working.

Does it make sense? Thanks

Joe Huggans’s picture

I could still not get things working with the dev 7.2 version unless I did the following.

Add another custom field, use tokens to grab value from the field you want to use in PHP field, exclude from display, then use that in the PHP code for the field. It is something like $row->nothing

But is a workaround!

I did try this with the current version and was getting errors so it seems the dev version is required

shahrokhi’s picture

shahrokhi’s picture

same problem here for me!
I want to get access to user field's value referenced from the node.
I have an entity referenced field to the user in my content type and I add relation for this in my view and I add user_custom_field in fields section of the view.
but $row->user_custom_field return the user's UID

Thanks

James Feng’s picture

Thank you very much liquidcms. #196 It's very useful to me.