Computing a field from a view

Last modified: March 25, 2009 - 17:51

Your mileage may vary, but here is some code which calculates a field based on a view.

This code may not do what you want— if the view changes (e.g. another node is added), this field would not be re-evaluated till the next time the node is saved.

One (ugly) solution is to put similar code into the header or footer of a view.

This is a coding alternative to the views_calc module, which allows a great deal of flexibility, but is perhaps not ideal.

<?php
$view
= views_get_view('YOURVIEWNAME');
$info=views_build_view('items', $view, array($node->nid), false, false);
$total=0;
//drupal_set_message(serialize($info));
foreach ($info['items'] as $item) {
 
$total+=$item->YOUR_FIELD_USE_THE_DEBUG_MESSAGE_ABOVE_TO_FIND_IT;
}
$node_field[0]['value']=$total;
?>

*_*

beautifulmind - July 21, 2009 - 02:49

Configured: Yes
Code added: Yes
But when I un-comment the message it does not showing any thing.

Regards.

*_*

beautifulmind - July 23, 2009 - 18:26

Also, throws error: call to undefined function views_build_view()

Views 2

Oliver Coleman - August 20, 2009 - 03:34

For Views 2 to insert the raw output from a view you just need something like:
$node_field[0]['value']=views_embed_view('YOUR_VIEW_NAME', $display_id = 'YOUR_DISPLAY' [, ARGUMENT 1, ARGUMENT 2, ...]);
More info on views_embed_view is at http://views-help.doc.logrus.com/help/views/embed

--
oliver@e-geek.com.au
http://e-geek.com.au - commercial web design.
http://enviro-geek.net - not-for-profit web services.

 
 

Drupal is a registered trademark of Dries Buytaert.