I have a cck multi-value field (field_images) and I'm trying to use the Computed Field module to calculate and display a count of images in a view. I know this is probably insanely simple to do, but I'm really not familiar with php and I've been tearing my hair out for two days.

I located the following snippet on the documentation for the Computed Field module:

$node_field[0]['value'] = count($node->field_images);

This works great if the node has one or more images. Nodes without any images still display a value of 1.

I would weep with gratitude if someone can help me figure this out :)


gpk’s picture

Enable/install devel module and use it to examine (e.g. using the dev load tab) $node->field_images for the cases of 0 and 1 images. There should be a difference that you can then detect and respond to in your code snippet.

whimsy’s picture

Thank you, gpk! The devel module did the trick. In case anyone else wants to know how to do this:

To count the number of values in a cck multi value field. In my case the number of images in a multi-value image field. When using the Computed Field module, put this code in the Computed Code field:

if (is_null($node->field_images[0]['fid']))
$node_field[0]['value'] = 0;
$node_field[0]['value'] = count($node->field_images);

Put this in the Display Format field:

$display = $node_field_item['value'];

It seems that when I add a node that has the field_images field, a row is created in the content_field_images table even if the node has no images. If there are no images, the field_images_fid field will be NULL. If you only count $node->field_images, the code will always return a minimum value of 1 because of that row in the table, even though it has a null value. So I had to first test for nodes with NULL in the field_images_fid field and return 0 for them. Hope that makes sense.

mori’s picture

Does this also work in D7?