Community Documentation

Computing a field from a view

Last updated March 25, 2009. Created by choster on October 1, 2007.
Edited by cbow, elcuco, markfoodyburton. Log in to edit this page.

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

Comments

*_*

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

Regards.

*_*

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

Views 2

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

Views 3

What about Views 3?

You may prefer Dynamic Field module

Dynamic Field module (http://drupal.org/project/dynamicfield) make a similar thing than computed field but don't store any values in database.
Dynamic Field computes the php whenever the node is rendered in the theme.

Then if the view result change, the node display change too, and all is fine.

what should be the code for Vews 3?

what should be the code for Vews 3?

This syntax worked for me in Drupal 7, Views 3

$entity_field[0]['value'] = views_embed_view('emails','page');

'emails' = THE NAME OF THE VIEW
'page' = THE NAME OF THE DISPLAY

I had a simple, one-field view that I wanted to display on the user account page. The above syntax did the trick. You may have to do some theming to get rid of the generated markup.

Hope this helps someone.

Matt

About this page

Drupal version
Drupal 5.x, Drupal 6.x
Audience
Programmers, Site administrators

Site Building Guide

Drupal’s online documentation is © 2000-2013 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License. Comments on documentation pages are used to improve content and then deleted.
nobody click here