Community Documentation

Merge mutiple fields into one

Last updated December 4, 2008. Created by mikeytown2 on December 4, 2008.
Log in to edit this page.

I have 2 option cck fields, one is a predefined list, the other is a text field. Both are set to unlimited number of values. I first tried to use array_merge, since it would be a more "elegant" solution; but I couldn't make it fly. This was my first attempt.

<?php
// set temp variable
$count = 0;

// put array into computed field array pt1
foreach (element_children($node->field_option) as $key) {
   
$node_field[$count]['value'] = $node->field_option[$key]['value'];
   
$count++;
}

// put array into computed field array pt2
foreach (element_children($node->field_option_list) as $key) {
   
$node_field[$count]['value'] = $node->field_option_list[$key]['value'];
   
$count++;
}
?>



To make this into a comma separated list, here is the code. This works with "Store using the database", while the top one doesn't for some reason. This is what I'm using now
<?php
// set temp variable
$temp = array();

// put array into computed field array pt1
foreach (element_children($node->field_option) as $key) {
   
$temp[] = $node->field_option[$key]['value'];
}

// put array into computed field array pt2
foreach (element_children($node->field_option_list) as $key) {
   
$temp[] = $node->field_option_list[$key]['value'];
}

//kill empty values in the array
foreach ($temp as $key => $value) {
    if (
is_null($value) || $value=="") {
        unset(
$temp[$key]);
    }
}

//implode to comma list
$node_field[0]['value'] = implode(', ', $temp);
?>

Comments

Is there more going on here

Is there more going on here than meets the eye?

I know changing the field to your specific type (like $node->field_YOURFIELD is required, but what else is needed to make this work?

Right now, that code (both of them) don't do anything.... or at least I don't see it doing anything..

This is for combining 2

This is for combining 2 option fields. They both contain the same kind of data (text). Try it out with 2 option fields. I haven't tried this with mixed data types.

Just for reference for future

Just for reference for future people seeing this thread: http://drupal.org/node/449206 see here for details

d7 - field collection

Also, for future searchers, maybe look into Field Collection. It's a new module, with a lot of the Drupal titans involved with it. It's beautiful if I do say so myself. Entities as fields, and before you get scared off, just consider that for a moment and look at the project page :)

About this page

Drupal version
Drupal 6.x

Site Building Guide

Drupal’s online documentation is © 2000-2012 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License. Comments on documentation pages are used to improve content and then deleted.