What they don’t tell you about Computed Fields

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.

  1. Don’t mess with or change the Display Code area, which has the following code:

    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’] :
  2. I was confused by the little helpful examples for getting node field values for use in computations (shown below):

    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.
  3. 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.