On this page
Configuring Computed Field
Last updated on
30 April 2025
Configuration
A Computed Field can be configured with the usual field options, as well as the following extra options:
- Computed Code
- This is the code that will assign a value to your computed field. It should be valid PHP without the <?php ?> tags.
- Display Code
- This is also PHP code which should assign a string to the $display_output variable. It has
$node_field_item['value'](pre-D7) or$entity_field_item['value'](D7+) available, which is the value of the computed field. It also has$field(and some language information, D7+) available, and you can call any Drupal functions you want to display your field. Alternately, the code can be supplied by your own custom function named computed_field_YOUR_FIELD_MACHINE_NAME_display(). See the main Computed Field documentation page for an example of how to implement it. - Store using the database settings below
- If this is checked then the field is computed on node/entity save and stored. If it isn't stored then it will be recomputed every time you view a node/entity containing this field. This option is required if you wish to access your field with the Views module.
- Database Storage Settings
-
- Data Type
- This is the SQL data type to use for storing the field contents in the database. Let us know if you need any other storage types, or if you would like an 'other' option :). For calculating dollars and cents, for example, you would choose the "decimal" option.
- Data Length
- This value will simply be passed on to SQL. For storing up to 10 digit integers (INTs), enter 10. For storing currency as a float, use 10,2 (unless you'll store larger than 10 figure amounts). For storing usernames or other short text with a VARCHAR field, 64 may be appropriate.
- Default Value
- Leave this blank if you don't want the database to store a default value if your computed field's value isn't set. Following the currency example above, you would set this to "0.00".
- Not NULL
- Leave unchecked if you want to allow NULL values in the database field. For things like currency, you probably want to check this.
- Sortable
- Used in Views to allow sorting a column on this field. (Pre-D7 only. May not be required in D7+.)
- Indexed
- Adds a simple DB index on on the computed values.
Tips
- If you want your field visible in Views, then store it in the database.
- If your stored field needs to access the node ID, then add
if (!$node->nid) node_save($node);at the start of your computed code. Otherwise the node might not yet have an nid. For Drupal 7+, use the $entity object instead of the $node object.
Help improve this page
Page status: Not set
You can:
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