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

Computed Field

fill node reference fields

Last updated on
30 April 2025

Our Example - This is code to fill node reference fields

We had a situation where we needed to fill three different reference node CCK fields. The city and county fields were being filled by geo location from openlayer module CCK wkt field type. The nearest city is a manual entry used by the editor of the node. Our situation is that the nearest city and the geo location's city could be the same or they could be different.

We wanted, if they were the same, that the reference would not be duplicated. So if they are the same we just set the node reference for one CCK field to NULL. Of course it might be obvious that we used three field entries that were not node references. The code below uses those three fields and some data base query to locate and provide the values in the reference fields.

We put the code into the Computed Code: field. Nothing is stored from this field directly to the database and the Display Format: We determined that the fields update when the record is merely viewed but the values were not saved. The event of editing the node also did not update the database and did not show the values in the node references. The final event of saving the node did update the database and made the entries more permanent.

Hope that this helps those of you who might need some additional ideas in this area. Thanks to your help - b.coleman (Drupal user name)

$result = db_fetch_array(db_query("SELECT n.nid, title FROM {node} n INNER JOIN {content_type_demographics} d ON n.nid = d.nid WHERE title = '%s' AND field_demographic_state_value = 'Texas' AND field_demographic_type_value = 'City'", $node->field_city[0]['value']));
$node->field_reference_city[0]['nid'] = $result[nid];
$node->field_reference_city[0]['value'] = $result[title];

if ( $node->field_city[0]['value'] != $node->field_nearest_larger_city[0]['value'] ) {

$result = db_fetch_array(db_query("SELECT n.nid, title FROM {node} n INNER JOIN {content_type_demographics} d ON n.nid = d.nid WHERE title = '%s' AND field_demographic_state_value = 'Texas' AND field_demographic_type_value = 'City'", $node->field_nearest_larger_city[0]['value']));
$node->field_reference_nearest_city[0]['nid'] = $result[nid];
$node->field_reference_nearest_city[0]['value'] = $result[title];
}
else {
$node->field_reference_nearest_city[0]['nid'] = NULL;
$node->field_reference_nearest_city[0]['value'] = NULL;
}

$result = db_fetch_array(db_query("SELECT n.nid, title FROM {node} n INNER JOIN {content_type_demographics} d ON n.nid = d.nid WHERE title = '%s' AND field_demographic_state_value = 'Texas' AND field_demographic_type_value = 'County'", $node->field_county[0]['value']));
$node->field_reference_county[0]['nid'] = $result[nid];
$node->field_reference_county[0]['value'] = $result[title];

Help improve this page

Page status: Not set

You can: