Counting the number of values in a multi value field
I have a content type containing a multi-value image field (field_images). The number of images that can be added is unlimited. I'm using the Computed Field module which allows me to use php code to calculate the number of images that have been uploaded and display that total in a view.
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;
}
else
{
$node_field[0]['value'] = count($node->field_images);
}
Put this in the Display Format field:
$display = $node_field_item['value'];
Initially, I only used the count function without the preceding if statement. This did count correctly for nodes having at least one image; however, it would return a value of 1 for any node with no images. By looking at the database table, I figured out 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 this helps somebody else. I'm not a coder, so it took me two days to figure this out.
Help improve this page
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion