Setting the Default Value of a CCK Field Using PHP Code

Each field in a CCK content type can be configured with a default value. This is particularly easy if the value is static - such as in a select or text field. When the default value needs to be set dynamically based on other factors, however, it is not nearly so easy. CCK provides users with the option of using PHP code to generate a default value. The example below fills in a user reference field with the currently logged in user for the assigned technician field.


global $user;
if (in_array('technician', $user->roles)) {
return array(0 => array('uid' => $user->uid));
}
else {
return array();
}

The code needs to return an array. The $user variable is a global variable that represents the currently logged in user. The code above checks that the user has the technician role (someone who can be assigned a work order). If the currently logged in user is a technician, the assigned technician field will default to their username. Otherwise, the code does not provide a default value.