How to split a cck field into a multiple values field (snippet)

Last modified: March 7, 2008 - 15:00

Install the 'devel'-module to be easily able to execute PHP code, adapt the following code to your needs:

split

This example splits the cck-field containing a concatenated list of multiple values (here authors in cck field 'authorlist') into their own place within another multiple value cck field (here 'authors'):

- selects nodes to change
- loop over nodes (while)
- cleans field 'authorlist'
- splits field 'authorlist' by semi-colon ;
- loop over split values (foreach)
- puts values into multiple values field 'authors'
- submits changes

<?php
$results
= db_query("SELECT * FROM {node} WHERE type='%s' ", "pub"); // AND nid BETWEEN 0 and 100
while ($my_node = db_fetch_object($results)) {
   
$node = node_load($my_node->nid);
   
_content_widget_invoke('prepare form values', $node);
   
$my_field = trim($node->field_authorlist[0]['value'],"; ");

   
$values = array();
   
$my_authors = explode(";", $my_field);
   
$my_delta = 0;

    foreach (
$my_authors as $my_author) {
       
$values['field_authors'][$my_delta]['value'] = trim($my_author);
       
$my_delta++;
    }
   
drupal_execute('pub_node_form', $values, $node);
}
?>

Execute twice/thrice (as many split values /3 you may have) as multiple values form only allows to insert three more values at once, ie at each preview-step (as we're using drupal_execute here).

join

The other way 'round, i.e. join/concatenate a multiple value field into a single value field:

<?php
$results
= db_query("SELECT * FROM {node} WHERE type='%s'", "pub");
while (
$mynode = db_fetch_object($results)) {
   
$node = node_load($mynode->nid);
   
_content_widget_invoke('prepare form values', $node);
   
$my_authors = array();
    foreach (
$node->field_authors as $my_author) {
       
$my_authors[] = $my_author['value'];
    }
   
$values['field_authorsconcat'][0]['value'] = implode("; ", $my_authors);
   
drupal_execute('pub_node_form', $values, $node);
}
?>

 
 

Drupal is a registered trademark of Dries Buytaert.