The Drupal Computed Field module is pretty handy. It allows you to add a hidden or visible field with a computed value based on user input in other fields. The value you compute is stored in a DB table and is accessible by Views and other modules. But, when I first installed the module and began working with it, I found that the documentation was awfully meager. Here are some things that I learned.
- Don’t mess with or change the Display Code area, which has the following code:
1$display_output = $entity_field_item['value'];
I had the silly idea that I could pass my own variable to $display_output instead of using $entity_field_item[‘value’]. Not so. You have to populate $entity_field_item[‘value’] in the Computed Code section above the Display Code area. At the end of your code that performs the computation, you just need to assign your results to $entity_field_item[‘value’] :
1$entity_field_item['value'] = $my_computed_variable
- I was confused by the little helpful examples for getting node field values for use in computations (shown below):
1$field_a = field_get_items($entity_type, $entity, "field_a");
Did I have to provide the $entity_type and $entity? Turns out, this is not necessary and all that is required is to substitute the machine name of your field for “field_a” in order to grab the value. $entity_type and $entity are already populated for you.
- For my computations, I wanted to obtain the title of the node. I wasn’t sure how to go about this. The node title is contained in a column of the node table in the database, whereas, node field data can be found in the last column of a table created just for one field’s data only. Each data field has it’s own table, which is keyed to the node table. I knew it was going to require something different to get the title. I had just been developing custom code for Drupal Rules and so kept going off in that direction, which didn’t work. The answer is actually very simple. To get the node title, just use:
The rest is just plain old PHP all done in the Computed Code area.