Setting Drupal CCK and Location Default Values
Published:
Heads up! This content is more than six months old. Take some time to verify everything still works as expected.
Had a bit of trouble setting default values for a location item
today. It seems I was outsmarting myself, or maybe location was
smarter than I gave it credit for. I couldn't seem to use
form_alter()
to set default values for the location field. The
values would appear, but nothing would happen on node save.
Strange...
The cause? It seems the location code checks if the values of the location fields are empty, or are equal to the default values for the location. So, if you set the default values of the fields to your user's address... his address counts as empty, because it's the default value.
The solution! Use nodeapi( $op = 'prepare')
! It should be noted
that this also works for cck fields' default values as well.
function hook_nodeapi_prepare(&$node, $a3 = NULL, $a4 = NULL){ if(!$node->nid){ global $user; // Default Values $node->field_first_name[0]['value'] = !empty($user_data['first_name'])? $user_data['first_name'] : ''; // $node->field_first_name[0]['format'] = !empty($user_data['first_name_format'])? $user_data['first_name_format'] : '1'; // If it's a filtered field, you need to include the format. $node->field_last_name[0]['value'] = !empty($user_data['last_name'])? $user_data['last_name'] : ''; $node->field_email[0]['email'] = !empty($user->mail)? $user->mail : ''; $node->locations[0]['street'] = !empty($user_data['street1'])? $user_data['street1'] : ''; $node->locations[0]['additional'] = !empty($user_data['street2'])? $user_data['street2'] : ''; $node->locations[0]['city'] = !empty($user_data['city'])? $user_data['city'] : ''; $node->locations[0]['postal_code'] = !empty($user_data['postal_code'])? $user_data['postal_code'] : ''; $node->locations[0]['province'] = !empty($user_data['province_name'])? $user_data['province'] : ''; $node->locations[0]['province_name'] = !empty($user_data['province_name'])? $user_data['province_name'] : ''; $node->locations[0]['country'] = !empty($user_data['country'])? $user_data['country'] : 'us'; } }