Community Documentation

Value conditional on whether other field is filled

Last updated January 30, 2009. Created by mpromber on January 30, 2009.
Log in to edit this page.

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 ... ?>)

<?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:

<?php
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!

About this page

Drupal version
Drupal 6.x

Site Building Guide

Drupal’s online documentation is © 2000-2013 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License. Comments on documentation pages are used to improve content and then deleted.