This example shows how to set and display multiple values for a computed field.

Enable the multiple values option for the computed field.

In earlier version of Drupal (5? 7?)

Computed Code

$node_field[0]['value'] = "en.wikipedia.org/wiki/Scrapheap_Challenge";
$node_field[1]['value'] = "abc.net.au";
$node_field[2]['value'] = "australia.gov";

Enable the 'display this field' option for the computed field.

Display Format

$display = l('A link to '.$node_field_item['value'],'http://'.$node_field_item['value']);

When computed field executes the output will be displayed as:
A link to en.wikipedia.org/wiki/Scrapheap_Challenge
A link to abc.net.au
A link to australia.gov

In Drupal 8

In Drupal 8, to populate a multi-valued field, a single value must still be returned, but your function will be called multiple times for each of your values (or "deltas"). So it's necessary to populate the full delta-keyed array, but then only return the value requested (for each delta).

Computed Code

Here is an example.

function computed_field_FIELD_NAME_compute($entity_type_manager, $entity, $fields, $delta) {
  // Fill in array values with data.  The keys are optional in this case as they are the defaults.
  $values = [
    0 => 'Dog',
    1 => 'Cat',
    2 => 'Mouse',
  ];

  // Return the single value currently requested by the system.
  return $values[$delta];
}

Comments

mikeytown2’s picture

Using Drupal 6 for my examples. This is when in CCK you set Number of values: to more then 1.

Computed Code

//Iterate through array. Output x, x, x, x and x

//set temp variables
$temp_field_x_array_length = count($node->field_x);
$temp_field_x_output = "";
$temp_field_x_counter = 0;

//main loop
for ($temp_field_x_counter = 0; $temp_field_x_counter < $temp_field_x_array_length-2; $temp_field_x_counter+= 1)
{
 $temp_field_x_output .= $node->field_x[$temp_field_x_counter]['value'] . ", ";
}

//second to last value
if ($temp_field_x_counter == $temp_field_x_array_length-2)
{
 $temp_field_x_output .= $node->field_x[$temp_field_x_counter]['value'] . " and ";
 $temp_field_x_counter +=1;
}

//last value
if ($temp_field_x_counter == $temp_field_x_array_length-1)
{
 $temp_field_x_output .= $node->field_x[$temp_field_x_counter]['value'] . "";
 $temp_field_x_counter +=1;
}

$node_field[0]['value'] = $temp_field_x_output;

Display Format

$display = $node_field_item['value'];




If your using the Content Taxonomy field change this

 $temp_field_x_output .= $node->field_x[$temp_field_x_counter]['value'] . 

into this for plain text output

 $temp_field_x_term = taxonomy_get_term($node->field_x[$temp_field_x_counter]['value']);
 $temp_field_x_output .= check_plain($temp_field_x_term->name) . 

or this for linked output

 $temp_field_x_term = taxonomy_get_term($node->field_x[$temp_field_x_counter]['value']);
 $temp_field_x_output .= l($temp_field_x_term->name, taxonomy_term_path($temp_field_x_term), array('rel' => 'tag', 'title' => $temp_field_x_term->description));

Grabbed from line 200 of content_taxonomy.module
Add in $temp_field_x_term = ""; at the top in order to declare your variable before using it. Also be aware that the ""; is missing from above so that you can use find and replace for the code.

Alex Malkov’s picture

Thank you very much!

mikeytown2’s picture

Computed Code

//display first and last value only: x - x

//set temp variables
$temp_field_x_array_length = count($node->field_x);
$temp_field_x_output = "";

//zero to one value
if ($temp_field_x_array_length == 1)
{
 $temp_field_x_output = $node->field_x[0]['value'];
}
//over one value
else
{
 $temp_field_x_output .= $node->field_x[0]['value'];
 $temp_field_x_output .=  " - ";
 $temp_field_x_output .=  $node->field_x[$temp_field_x_array_length-1]['value'];
}

$node_field[0]['value'] = $temp_field_x_output;

Display Code

$display = $node_field_item['value'];
firfin’s picture

And is it also possible the display the values as a select box? I don't think thats possible using the "display format"?
It does state however I can supply my own computed_field_field_FIELDNAME_compute() function. But where do I put that function? And are there any examples for this kind of function?

devkinetic’s picture

I second this question!

Ryan aka Devkinetic
Sr. Web Developer

ryanaghdam’s picture

The functions go in your template.php file. The function signature should be: computed_field_field_FIELDNAME_compute($node, $field, &$node_field).

The $node argument passes the current node object. You will have access to all fields on the current node as well as fields that have already been calculated.

$node_field is a reference to the field you are modifying. In most uses, you will set $node_field[0]['value'] to the result, instead of returning it.

scarer’s picture

I copied the example at the top of the page perfectly and computed field is still not working for me. Is there something I am missing? These are the steps I took.

I added a new computed field to a content type.

I set the computed code values to:

$node_field[0]['value'] = "en.wikipedia.org/wiki/Scrapheap_Challenge";
$node_field[1]['value'] = "abc.net.au";
$node_field[2]['value'] = "australia.gov";

I set the display format value to:

$display = l('A link to '.$node_field_item['value'],'http://'.$node_field_item['value']);

It still isn't appearing on the node editing form.

Can someone please let me know if I've missed something?

Cheers,

S

kmdesign’s picture

Newbie here... I'm trying to capture the average of a field's multiple fields (its array of fields). Some research into PHP syntax revealed a seemingly easy way to get the sum of an array (array_sum), so I built the below bit of code, to be used in a Computed field type.

I want to use a multi-fielded field, so I don't have to create fields for each score, or write code to look for empty/null's, which if calculated as "0" would render the average inaccurate. The code is probably quite flawed, but I'm at my limit of understanding PHP (but still working at it). Any help is appreciated.

Computed code:
$average = array_sum($entity->field_multiple) / count($entity->field_multiple);

Display Code:
$display_output = $entity_field_item['$average'];

drupal a11y’s picture

For D6 the solution is posted here: http://drupal.org/node/879404

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;
}
else
{
$node_field[0]['value'] = count($node->field_images);
}

Put this in the Display Format field:

$display = $node_field_item['value'];

But how do I achieve this for D7?

mattcasey’s picture

Works in D6 and D7:

$i = 0;
for(element_children($elements) as $cid) {
  $elements[$cid]['value'] = $something; // $cid is the key of an element
  $i++;
}
print $i; // Returns total # of children
hockey2112’s picture

I am using Drupal 7. I have a a fleet of cars for which I am tracking the total miles driven. Each car is a separate content item. I have an integer CCK field in each of those Car content items called "Miles Driven", and the field is set to be "unlimited", so the user can add new "Miles Driven" as needed. Then, I have a computed field that should simply add up those "Miles Driven" field entries for that car. There could be two "Miles Driven" entries, or there could be 100... it all depends on how often that car is driven. Once I have that total "Miles Driven" value, that field will be used in other calculations... the problem is, I don't know how to add up those multi-value fields to get that total number of miles.

Can this code snippet be modified to automatically pull in all entries for that "Miles Driven" field for that car content item? I would be willing to pay for assistance to achieve this functionality if it is something that would require more than just a quick snippet of code.

==================

EDIT: I found my answer here: http://drupal.stackexchange.com/questions/39257/sum-of-integer-vaules-of...

$field_items = field_get_items($entity_type, $entity, 'field_miles_driven');

$total = 0;
foreach ($field_items as $item) {
$total += $item['value'];
}

$entity_field[0]['value'] = $total;

vmevada102’s picture

The above said soluton work for the main field, but i need to sumup the subfield of multifield and calculated field module in Drupal 7.

In my content type I had created the content type "invoice" with the following fields

  • Customer
  • Invoice num
  • Date
  • Products (multi field) subfield : description, price, quantity and amount.
  • Subtotal (computed field)

Now my problem is, I could not sum up the different values of the field_amount field.... Which is the subfield of the field_product main field.

Please let me know how can I sum up all my values which are array of all value as Subtotal field in my content type.

smowky’s picture

Im working on something that is very similar to your

content type:project
fields:

  • field_multifield
  • and its subfields

    • field_product_width
    • field_product_height

    and computed field

  • field_square_metre_together
  • here is as far is i could get:

    function computed_field_field_square_metre_together_compute(&$entity_field, $entity_type,$entity,$field, $instance, $langcode, $items) {
         //here check whether its nonempty	
         if (isset($entity->field_multifield[LANGUAGE_NONE][0]['field_product_height'][LANGUAGE_NONE][0]['value']) &&
         isset($entity->field_multifield[LANGUAGE_NONE][0]['field_product_width'][LANGUAGE_NONE][0]['value'])) {
         //here multiply w*h
    	$entity_field[0]['value'] = $entity->field_multifield[LANGUAGE_NONE][0]['field_product_height'][LANGUAGE_NONE][0]['value']
    		* $entity->field_multifield[LANGUAGE_NONE][0]['field_product_width'][LANGUAGE_NONE][0]['value']; 
    			}
    		else $entity_field[0]['value'] = 0;
    }
    
    

    what i was thinking next is with go value of delta
    field_multifield[LANGUAGE_NONE][$delta]['field_product_width'][LANGUAGE_NONE][$delta]['value'];
    somehow through foreach loop, but here i got stucked
    idea behind is be able to store multiple values of field_square_metre_together
    maybe someone with better knowledge of php might help?

    vmevada102’s picture

    Hello smowky ,

    Thanks for your reply,

    Kindly find the attached screenshot for my problem....

    download file from below

    https://sites.google.com/site/vmevada102/downloads-1/Presentation1.jpg?a...

    Please help me to do the same calculations....

    share the codes for doing this

    smowky’s picture

    Hi
    You cannot compute field from other computed field
    Because value of computed field_amount is known after node is sumitted
    So for field_subtotal you cannot use field_amount but u have to do all the math again.

    Btw how did you managed to have a working computed field inside multivalue?

    vmevada102’s picture

    Hello,

    Actually, i had used the field_amount is calculated using the computed field module.

    But i could not get the calculation for the field_subtotal.

    Do you have any suggestions to do the same.

    Moniroaf’s picture

    i have problem in multiple values using RESFUL API is that
    i have field it has multi values in it, but when i did patch Method to add another value, all the values that in the field before will delete and the new value will add
    so i want to know how i can add the new value with the old values without change by using RESTFUL API (POST, GET, PATCH, PUT) and which one from these method i have to use ?
    anyone he had this problem before or he did it before?
    Thanks

    kaelteschutzgebiet’s picture

    First of all, thank you for this example.
    My problem is, that it only works if I add the right number of fields to the node while editing it.
    I have a php code that generates an array $values with a number of values that is then added with $delta (just like the example).
    When I first save the node it will show one value. After the second saving process without changing anything, it shows the first two values and so on until I saved the node n-1 times (n is the number of values in $values).

    Is there any way to set the number of values for a multi-value field explicitly?
    I can't do this in the "manage fields" page because the number of values is changing from page to page.

    designcrs’s picture

    We do have the same problem. Did you ever find a solution?

    kaelteschutzgebiet’s picture

    No, I never found a solution for that, sorry. The project was shut down shortly after.
    However, if you find a solution, I'd be happy to hear about it.

    designcrs’s picture

    Thanks for getting back to me!
    3.0.0.-alpha2 "Stops displaying empty values and adds support for computed cardinality" which fixes our problem.

    The field to enter the code in the UI has been removed. After placing the code in a separate module using the function name as stated in the module's backend it does work now: The amount of field values now automatically matches the count of the array "$values".

    However, when saving the node the computing code is being executed many many times for no obvious reason. In some cases this won't be noticeable, but in my case this causes heavy file processing to be done repeatedly. Very undesirable!

    designcrs’s picture

    Note: Multi-valued computed fields do not work properly in 2.x (even the Dog-Cat-Mouse example above does not work correctly)!
    Multi-valued computed fields are only usable starting with 3.x!