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 }

Comments

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.

Same problem here..

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.

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

Same issue as above ruining the fun :(

i'm guessing this is a duplicate for

http://drupal.org/node/1061388

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

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

try $data in the output field.

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

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

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.

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.

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

<?php
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 ?

+1 would be great to fix this issue

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:

<?php
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
<?php
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.

subscribe

subscribe

same issue

+1

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>

;-)

+1

subscribe

Category:support» bug

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

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

subscribe

+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".

@Bobik

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

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

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...

+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.

StatusFileSize
new3.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 ...

Sub

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.

@ Stakcreativa

Thanks so much for trying to help. I put that in the Output field with the

<?php
...
?>
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

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.....

<?php
$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

@Stakcreativa

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

nice rv0 =)

+1

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

@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

<?php
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().

@Stakcreativa

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

Tim

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

<?php
$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.

Tried this as a php filter with no luck.

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

Tried this as a php filter with no luck.

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

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.

<?php
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
...)
<?
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?

Status:Active» Needs review
StatusFileSize
new1.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 :
    <?php
    if (isset($data->_field_data)) {
    return
    $data->field_field_myfield[0]['rendered']['#markup'];
    }
    ?>

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.

Title:Variables not returning correct valuesIn 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>';
}
?>

Title:variables not returning correct valuesVariables not returning correct values

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

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.

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!

Subscribe

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

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?

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.

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

Bump

subscribe

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??

@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.

StatusFileSize
new4.17 KB

Oops, here's the promised combines patch.

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

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.

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'];

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

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

:|

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.

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.

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

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.

#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];

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);

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.

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

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?

Issue summary:View changes

Clearer description of issue.

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

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

Issue summary:View changes

More detailed solutions

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.

StatusFileSize
new124.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.

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.

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

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

<?php
// 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, ',', ' ');
?>

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

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!

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']) ;

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.

This allowed us to pull taxonomy terms:

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

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.

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.

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.

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

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

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?

Yes, #88 worked for me using

dsm($data);

to target the field and value.

S

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.

@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.

@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.

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

subscribe

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

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

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

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?

@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

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

<?php
if (count($data->field_field_gender) == 2) {
  print
'Unisex';
}
else {
  print
$data->field_field_gender[0]['rendered']['#markup'];
}
?>

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

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?

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!

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.

No news?

@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.

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

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

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

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

but:

<?php
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.

StatusFileSize
new47.73 KB

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!

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

@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.

@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.

StatusFileSize
new186.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

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.

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
)

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.

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:

<?php
$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.

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.

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

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

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:

<?php
  $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');
?>

$row->path shows NULL.

Workaround:

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

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.

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...

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>";

subscribe

Hi,

I have used

<?php
$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.

Issue summary:View changes

added reference to 1516348

Subscribe

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.

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

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.

<?php
   
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.

<?php
   
// 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.

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


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

@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.

Guys, how should I print body value?

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

Thanks,
Szy.

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:

<?php
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'];
?>

Nope, I still have this problem too.

Szy.

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

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

<?php
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:
<?php
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', ), )

@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'];

@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?

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.

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.

Issue summary:View changes

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.

Status:Active» Needs review
StatusFileSize
new893 bytes

So here's a potential fix.

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.

Status:Needs review» Reviewed & tested by the community

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

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) ?>”>

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

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...

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.

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?

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

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.