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.

Comments

Code Rader’s picture

If you aren't working with the title then you don't need the first node_save.

I was getting a WSOD on new node creation with that. Editing existing nodes was ok, but node_save on a new node caused the WSOD with no errors in the log or anywhere else.

Jeff Rader

Clint Eagar’s picture

I used this conditional statement to calculate prices:

if (!$node->nid) {
	node_save($node);
}

if (($node->field_service_time_override[0]['value']) && ($node->field_bill_rate_override[0]['value'])) {
	$node_field[0]['value'] = $node->field_service_time_override[0]['value'] * $node->field_bill_rate_override[0]['value'];
}
else if ($node->field_service_time_override[0]['value']) {
	$node_field[0]['value'] = $node->field_service_time_override[0]['value'] * $node->field_bill_rate[0]['value'];
}
else if ($node->field_bill_rate_override[0]['value']) {
	$node_field[0]['value'] = $node->field_service_time[0]['value'] * $node->field_bill_rate_override[0]['value'];
}
else {
	$node_field[0]['value'] = $node->field_service_time[0]['value'] * $node->field_bill_rate[0]['value'];
}

Thank you for your example, it helped a lot!