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;
 }

Submitted by Jonathan Mitchell on Thu, 03/26/2009 - 11:20

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
enrique (not verified) Says:
Thu, 08/20/2009 - 22:34

Thanks!!

Brett (not verified) Says:
Thu, 06/18/2009 - 03:38

Thanks! You just saved me a lot of time trying to figure out how to do this. And thanks to Google for matching my search phrase "cck allowed values" directly to this post. Woot.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.