Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
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
WSOD on node add
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
Much thanks!
I used this conditional statement to calculate prices:
Thank you for your example, it helped a lot!