background image
Eric's picture

This problem comes up a lot in my Drupal module development: How do I generate the html for an individual CCK field? After much examination of the CCK, Views, and Node modules, I came up with this code snippet:

<?php
// load the node object
$node = node_load(MYNODEID);

// at this point the node object contains preprocessed data. build the content
$node = node_build_content($node);

// loop through content
foreach ($node->content as $k => $v) {
 
// specify a delimiter
 
$delimiter = "\n";

 
// ensure field items exist
 
if (is_array($v['field']['items'])) {
   
// create a container for the items html
   
$content = array();

   
// loop through items
   
foreach($v['field']['items'] as $i) {
     
// theme item
     
$content[] = theme($i['#theme'], $i);
    }

   
// roll up items html using delimiter
   
$content = implode($delimiter, $content);
  } else {
   
// NOTE: drupal_render includes divs, field labels, etc, which you may not want
   
$content = drupal_render($k);
  }

 
// NOTE: at this point, the data will be stored in $content, and you can now do whatever you want with it.
  // The date module gave me some headaches with this code snippet, BTW

}
?>