Advertising sustains the DA. Ads are hidden for members. Join today

Contributed modules documentation

Computed Field

Computed Field is a module that lets you add a computed field to custom content types. You can choose whether to store your computed field in the database, or simply have it calculated upon view. You can also choose whether to display the field, and how to format it. The value of the field is set using PHP code so it can draw on anything available to Drupal, including other fields, the current user, database tables, etc. The drawback of this is of course that you must be PHP-savvy to use it.

Before you can use Computed Field for versions prior to Drupal 7, you'll need to get CCK and enable (at the very least) the 'content' module. You will probably also want to enable the other cck modules, such as 'text', 'number', 'date', etc.

Before you can use Computed Field for Drupal 7+, you'll need to enable the Field module. You will probably also want to enable the 'Field UI' module and other field
modules, such as 'Text','Number', etc.

To add a computed field to a content type, go to Administer > Content > Content types (pre-D7) or Adminstration > Structure > Content types (D7), select the content type you want to add to, and click on the 'Add field' tab (pre-D7) or fill in the "Add new field" line (D7). One of the field types available should be 'Computed', and it should have a single widget type available to it, labelled 'Computed'. If you select this, give your field human-readable and machine-readable names, and submit the form, you will get to the configuration page for your new computed field.

For details on configuration, see the Configuring Computed Field page.

When is the field actually computed?

If you wish to store the values in the database then you have to update or re-submit the node to compute the value of the field.

If it is not stored in the database then the value computes when the node loads and only when the node is loaded. The field will not work in views nor will it function properly if it depends on other non-stored computed fields.

Examples

Drupal 6

See the README and sub-pages for examples. Also see #858970: custom function hook help is incomplete for an important note about using a .module file to compute the value(s) for a field.

Drupal 7

As described above, to set the value of the field, set $entity_field[0]['value']. For multi-value computed fields continue with $entity_field[1]['value']. Here's a simple example which sets the computed field's value to the sum of the number fields field_a and field_b in a node entity:

  // Simply return the sum of the two other fields.
  $field_a = field_get_items($entity_type, $entity, 'field_a');
  $field_b = field_get_items($entity_type, $entity, 'field_b');
  $entity_field[0]['value'] = $field_a[0]['value'] + $field_b[0]['value'];

field_get_items() saves you from having to deal with languages; you'll always get the current one, even if language-neutral.

Note that when setting values for $entity_field, you should not set specific language codes. These have no place here, and are not necessary for the field to function properly.

To see details of the arguments provided to you, enable the Devel module and use dd() or a similar function to output the full contents of each argument.

Drupal 7 example usage:

How to write the computed field override function

Drupal 6

Alternately, the code can be supplied by your own custom function named computed_field_FIELD-NAME_compute($node, $field, &$node_field). Note the ampersand in the &$node_field argument - it must be passed by reference to ensure changes are kept. Here's an example of how to do this:

function computed_field_FIELD-NAME_compute($node, $field, &$node_field){
    // Change the value of the field
	$node_field[0]['value'] = 'foo';
}

Drupal 7

To use a function in a custom module instead of writing the code in text area create a function that looks like:

function computed_field_YOUR_FIELD_MACHINE_NAME_compute(&$entity_field, $entity_type, $entity, $field, $instance, $langcode, $items) {
  $entity_field[0]['value'] = 'value';
}

Parameters:

  • &$entity_field - The computed field. Used to store the computed value.
  • $entity_type - The entity type: node, user, comment, etc.
  • $entity - The actual entity (a node, user, comment, etc.)
  • $field - General field settings.
  • $instance - Field instance settings.
  • $items - The list of items.

Note:
Make sure $entity_field is passed by reference.

How to write the computed field display function

Drupal 6

function computed_field_YOUR_FIELD_MACHINE_NAME_display($field, $element) {
  $markup = isset($element['#item']['value']) ? $element['#item']['value'] : '';
  return $markup;
}

Drupal 7

Here is a clear example. Note the necessary arguments:

function computed_field_YOUR_FIELD_MACHINE_NAME_display($field, $entity_field_item, $entity_lang, $langcode, $entity) {
  return '$' . number_format($entity_field_item['value'], 2);
}

Drupal 8

Here's how you get the value of a field in a referenced entity:

$value = $entity->field_a->entity->field_b->value;

Simple example for a star formatter in Drupal 8

<?php

/**
 * @file
 * Contains \Drupal\Core\Field\Plugin\Field\FieldFormatter\PD5CustomFormatter.
 */

namespace Drupal\pd5_custom\Plugin\Field\FieldFormatter;

use Drupal\computed_field\Plugin\Field\FieldFormatter\ComputedPhpFormatterBase;
use Drupal\Core\Field\FieldItemInterface;

/**
 * Plugin implementation of the 'PD5_Custom' formatter for computed fields Gesamtbewertung.
 *
 * @FieldFormatter(
 *   id = "PD5_Custom",
 *   label = @Translation("PD5 Formatter Gesamtbewertung"),
 *   field_types = {
 *     "computed_integer",
 *     "computed_decimal",
 *     "computed_float",
 *   }
 * )
 */
class PD5CustomFormatter extends ComputedPhpFormatterBase {

  /**
   * Do something with the value before displaying it.
   *
   * @param mixed $value
   *   The (computed) value of the item.
   * @param \Drupal\Core\Field\FieldItemInterface $item
   *   The item to format for output
   * @param int $delta
   *   The delta value (index) of the item in case of multiple items
   * @param string $langcode
   *   The language code
   * @return mixed
   */
  public function formatItem($value, FieldItemInterface $item, $delta = 0, $langcode = NULL) {

    $rounded = round($value, 0);
    $markup = '';

    switch ($rounded) {
      case 0:
        $markup = "<div class='starrating'>";
        $markup .= "<span class='rate-value'>$rounded</span>";
        $markup .= "<span class='rate-image star-off odd s1'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-off even s2'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-off odd s3'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-off even s4'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-off odd s5'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-off even s6'><i class='fas fa-star'></i></span>";
        $markup .= "</div>";
        break;

      case 1:
        $markup = "<div class='starrating'>";
        $markup .= "<span class='rate-value'>$rounded</span>";
        $markup .= "<span class='rate-image star-on odd s1'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-off even s2'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-off odd s3'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-off even s4'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-off odd s5'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-off even s6'><i class='fas fa-star'></i></span>";
        $markup .= "</div>";
        break;
      case 2:
        $markup = "<div class='starrating'>";
        $markup .= "<span class='rate-value'>$rounded</span>";
        $markup .= "<span class='rate-image star-on odd s1'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-on even s2'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-off odd s3'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-off even s4'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-off odd s5'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-off even s6'><i class='fas fa-star'></i></span>";
        $markup .= "</div>";
        break;
      case 3:
        $markup = "<div class='starrating'>";
        $markup .= "<span class='rate-value'>$rounded</span>";
        $markup .= "<span class='rate-image star-on odd s1'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-on even s2'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-on odd s3'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-off even s4'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-off odd s5'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-off even s6'><i class='fas fa-star'></i></span>";
        $markup .= "</div>";
        break;
      case 4:
        $markup = "<div class='starrating'>";
        $markup .= "<span class='rate-value'>$rounded</span>";
        $markup .= "<span class='rate-image star-on odd s1'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-on even s2'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-on odd s3'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-on even s4'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-off odd s5'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-off even s6'><i class='fas fa-star'></i></span>";
        $markup .= "</div>";
        break;
      case 5:
        $markup = "<div class='starrating'>";
        $markup .= "<span class='rate-value'>$rounded</span>";
        $markup .= "<span class='rate-image star-on odd s1'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-on even s2'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-on odd s3'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-on even s4'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-on odd s5'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-off even s6'><i class='fas fa-star'></i></span>";
        $markup .= "</div>";
        break;
      case 6:
        $markup = "<div class='starrating'>";
        $markup .= "<span class='rate-value'>$rounded</span>";
        $markup .= "<span class='rate-image star-on odd s1'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-on even s2'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-on odd s3'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-on even s4'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-on odd s5'><i class='fas fa-star'></i></span>";
        $markup .= "<span class='rate-image star-on even s6'><i class='fas fa-star'></i></span>";
        $markup .= "</div>";
        break;
    }

    return $markup;

  }



}

Add Hebrew Date using a custom field

Following instructions are the product of a forum discussion taken in Drupal Israel site: http://www.drupal.org.il/node/3749 and are based

Adding a field to a vocabulary

This snippet takes a variable $my_field and inserts it as a term in a vocabulary. It also checks for existing terms with the same name and

Adding an 'auto_increment' field

There's now a module to do this, Serial Field, I recommend you to use that one instead of this option

CCK Taxonomy - accessing term names not just term ids

This is a suggestion for another code snippet. If you try to pull the data from a CCK Taxonomy field, you get the Term ID and not the actual

Calculate Subscribe/Unsubscribe links for forum topics (requires Notifications module)

The objective was to provide a CCK field that contains a link to either subscribe or unsubscribe for the node, depending on the current

Calculate Total Price based on number of items purchased

Here is an example code where the requirement is to calculate 'Final Price' based on the number of items the user is willing to purchase.

Calculating Call Center costs of CSRs

We had a client that wanted to calculate the amount of money people spend on transferring help-desk calls to Customer Service

Calculating a duration given a start and end time

This example uses KarenS' Date module to create a date field, "field_date", with both a start time and an end time that records hours and

Calculating age from birthday

PLEASE NOTE These snippets are user submitted. Use at your own risk.

Calculating average speed

D'Arcy Norman has a Computed Field example in which he calculates the average speed of a bike trip, rather than filling it in manually:

Calculating depreciation and valuation

Here are a couple of snippets designed to calculate the straight-line depreciation and the estimated current value of a given node.

Calculating diff between two fields

This compares the values of two text fields using PEAR.

Calculating total time taken to finish a race

The following method illustrates how to calculate, time taken by a rider to finish a race.

Compute Twitter URL by collecting Twitter IDs

I am creating a directory and added some fields for harvesting Social Media info - mainly Twitter and Facebook on a CCK content type called

Computed Field : audio file duration using getID3

To do this in Drupal 7 first install two modules : getID3() and Computed Field.

Computed Field code snippets

This is a collection of sample code snippets that can be used in CCK fields enabled by the Computed Field module.

Computed Fields: Adding numeric values stored in two separate fields (basic info).

Note: the Computed Field Module can be used instead of this custom code (in Drupal 5.x and 6.x)

Computed field: Calculate duration of CCK video field

If you have installed video and ffmpeg_wrapper modules and want to calculate duration of your video CCK field in Computed field in the

Computing a field from a view

Your mileage may vary, but here is some code which calculates a field based on a view.

Configuring Computed Field

Configuration

Converting Horsepower (float) into Kilowatts (float) and custom format it

As i was building a client site, i had a request like this: when he creates a node (Vehicle content type), among all the fields, he fills in

Converting currency

I used this snippet with the currency api and the Money CCK modules.

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

Create age groups of visitors

I maintain a community website and want to find out the age groups of my visitors. This age group is used for various purposes that require

Creative Commons and Copyrights

I tried out the excellent http://drupal.org/project/creativecommons_lite module (and a few years ago, back when 4.7.x was the rage http:/

Dublin Core and Head link tags

This code might work in a template file with some tweaking.

Exploding a string snippet

How does one 'chop up' a field you ask?

Extract First / Last Name from Title

I worked on a few sites that stored authors / persons in the normal form of First Name - Last Name:

Fill a non-computed field

Have you ever had a a case when you have a field that you want to be filled with data from other sources but you also want the field to be a

From a user profile (or other content type) check for role(s) of the author

I recently wanted a view display to list a number of user profile account information. Some of the user accounts have been "moderated" and

Generate A Random Number, Apply a Check Digit

I needed to create a field that would contain a unique serial number for certain node types. Using Computed Field, this was pretty easy. But

List Ubercart product options in two balanced columns

I wanted an "available options" type of field. This is a product (camp stove) that needs to be sized specifically for a given pot. When the

Major Revision Only Timestamp

We ran into a scenario where we needed to sort nodes by the last MAJOR revision timestamp (ie. only when they ticked the Revision checkbox).

Making Computed Field work with Flexifield

Many people have stated that Computed Field will not work with Flexifield.

Making a node link to itself

These examples demonstrate how to output the node ID (nid) for the current page in the form of a link to itself.

Merge mutiple fields into one

I have 2 option cck fields, one is a predefined list, the other is a text field. Both are set to unlimited number of values. I first tried

Multiple images upload with ImageField via FTP

This snippet allows multiple images upload with ImageField module via FTP Client.

Reference a CCK field from a different content type

If you have two different CCK content types and you want to reference information in one from the other, one way of doing that is to setup a

Show title of parent node in node heirarchy

here is the code to solve this:

Store "Form Multicrud" module array in a CCK Computed field

Hello,

Storing checkboxes in a single CCK field as comma separated values for performance reasons

I was unhappy with the way CCK stores multi value options widgets, as for each value it adds a separate row in a content field table. I had

Stripping out junk from embed codes (regex between tags)

I had a situation in which users were given the ability to embed content from a third-party provider. The default embed code contained a

Sum all CCK number fields from all nodes

I maintain an internal website that serves as an accounting back end to a firm. A content type is created that records general journal

Use with nodereference count

Additional Modules involved: www.drupal.org/project/Nodereference_count

Using Computed Fields inside and outside of Unlimited Value Multigroups

Here is a working code example that contains computed fields in

Value conditional on whether other field is filled

Note that I am a total Drupal and PHP newbie, so use this at your own risk. Works for me - so far :)

Working with multiple values

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

fill node reference fields

Our Example - This is code to fill node reference fields

getting data from a nodereferrer

I have the nodereferrer module installed and want to use data in a field in the node that refers to this node. This is the code I used

picture gallery local to node content

I have looked for a simple way to show individual image type CCK fields within the node content. This seems to have been the best solution

Guide maintainers

criznach's picture