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

Computed Field

Value conditional on whether other field is filled

Last updated on
30 April 2025

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

Here is my example:

  • For content type "story", I have a field "Short title" (field_short_title).
  • This field is not required.
  • I want a computed field that has the same value as the contents of field_short_title if the user has filled it in, else the same value as the node title.

Computed code: (without surrounding <?php ... ?>)

if (!$node->nid) {
node_save($node);
}
if (!$node->field_short_title['0']['value']) {
$node_field[0]['value'] = check_plain($node->title);
}
else {
$node_field[0]['value'] = check_plain($node->field_short_title[0]['value']);
}

The first if-statement is needed because in a newly edited node, the node title is empty and would return null. (Thanks for other code snippets here that helped me figure that out!)

And a friendly hint for newbies that you need to update existing nodes before they get the value in their computed field.

Help improve this page

Page status: Not set

You can: