Getting the allowed values for a Drupal 6.0 CCK field

Content

Getting the allowed values for a Drupal 6.0 CCK field

Posted in:

When programmatically creating Drupal 6.0 nodes incorporating CCK fields it may be useful to know the allowed values for the field prior to submitting your form with drupal_execute().

NOTE: the listed function is otiose. Views supplies the required
functionality already.

 
  $content_field = content_fields('field_make');
  $allowed_values = content_allowed_values($content_field);

The following function returns an array of the allowed values for a CCK field.

 
/**
 * Get array of allowed values for a cck field
 */
 function get_cck_field_allowed_values($field_name)
 {
   // read the field
  module_load_include('inc', 'Content', 'includes/content.crud');
  $fields = content_field_instance_read(array(field_name => $field_name));
  
  // explode the allowed values
  $allowed_string = $fields[0]['allowed_values'];  // string with \r\n separators
  $allowed_values = explode("\r\n", $allowed_string);

  // return keys if present
  $key_values = array();
  foreach ($allowed_values as $allowed_value) {
    $pos = strpos($allowed_value, '|', 0);
    if ($pos !== false) {
      $allowed_value = substr($allowed_value, 0, $pos);
    }
    $key_values[] = $allowed_value; // add to array
  }
  
  // take a peek using the developer module
  //dvm($key_values, 'Allowed values for field '.$field_name);
  
  return $key_values;
 }