I've spent all day trying to figure this out;

I have a user profile with a custom field, let's say 'Animals', where users can tick checkboxes for what animals they own, and I want to display them in their user profiles. I'm using Contemplates. When I try to print them, they come out like this:

---
Animals:
Dog
Cat
Hamster
Rabbit
---

However, I would like it to display like this:

---
Animals: Dog, Cat, Hamster, Rabbit
---

Or even like this, if at all possible:

---
Animals: Dog, Cat, Hamster and Rabbit
---

I've been trying implode, explode and all kinds of stuff, and searched the forums 'till I was blue in the face, but I've found nothing to help me along (you've probably guessed by now that I'm no PHP whiz)...

If someone could help, I would appreciate it greatly! Thanks!

joeboris

Comments

nancydru’s picture

Is there a div wrapper around the list? Is it set with LI tags? If so, you can use CSS to collapse the list, but that won't put the and in it.

As for doing the list programatically, take a look at the examples at http://us.php.net/manual/en/function.implode.php. Especially the comment from "richard at happymango dot me dot uk".

Nancy W.
Drupal Cookbook (for New Drupallers)
Adding Hidden Design or How To notes in your database

joeboris’s picture

Thanks for the tip, Nancy! I've been playing around with the implode2() function proposed by richard at happymango for a while, but as my programming skills aren't quite up to scratch, it's been quite a lot of shooting in the dark...

I have looked at styling it with css also, it was my first reflex in fact, but it's quite hard getting the result I wanted, with commas and all...

I'm actually rather amazed that this is such a big problem... I've started the last phase of the building of my site, touching up small details here and there, and I figured that this would be a breeze to fix... Imagine my surprise when I couldn't find anything covering this in the forums!

Anyway, further ideas would be greatly appreciated, and if I figure it out by myself, I will be sure to post my findings!

Thanks!
joeboris

nancydru’s picture

That looks pretty straight-forward, but I haven't tried it.

I suspect you won't find a lot of programming type tips here because those are php, rather than Drupal.

You might also check at http://www.phpfreaks.com

Nancy W.
Drupal Cookbook (for New Drupallers)
Adding Hidden Design or How To notes in your database

joeboris’s picture

      <?php 
function implode2($glue1, $glue2, $array)
{
    return ((sizeof($array) > 2)? implode($glue1, array_slice($array, 0, -2)).$glue1 : "").implode($glue2, array_slice($array, -2));
}

foreach ($field_animals as $value){
$array = array($value);
}
echo implode2(', ', ' and ', $value);

	
	?>

...but it displays:

---
Animals: Rabbit and Rabbit
---

instead of:

---
Animals: Dog, Cat, Hamster and Rabbit
---

Looks like this is the way to go though. Just have to sort out how to call the field values... Thanks again for the link, Nancy!

nancydru’s picture

I don't know your original structure, so this could be even simpler.

  $animals = array();
  foreach ($field_animals as $value) {
    $animals[] = $value;
  }
  echo implode2(', ', ', and ', $animals);

Nancy W.
Drupal Cookbook (for New Drupallers)
Adding Hidden Design or How To notes in your database

joeboris’s picture

Hi again!
Thanks, but the code displays a lot of Array, as so:

---
Animals: Array, Array, Array and Array
---

It displays the correct number of words, just not the right ones....

nancydru’s picture

I wasn't thinking real clearly on this. (I'm relatively new to CCK.) What is the format of $field_animals? If it's already an array, you just implode it. If it's a comma separated list, then $animals = explode(',', $field_animals); and then implode it. Either way you don't need the "foreach" (that I don't think is right to start with).

Nancy W.
Drupal Cookbook (for New Drupallers)
Adding Hidden Design or How To notes in your database

joeboris’s picture

I'm not sure what kind of format $field_animals is.. It's basically a straight-up cck text-field (a multiple select checkbox in the submission form). By default, it displays each value on a separate line, but I wanted them inline.

This I could fix with css, but I also wanted them comma-separated. If the and was possible, I would regard that as a bonus, but I basically just want to display the text-field values (Cat, Dog etc.) inline and comma-separated...

I've tried just printing the field like this:

<?php
print implode2(', ',' and ', $field_animals);
?>

...and this also returns:

---
Animals: Array, Array, Array and Array
---

In my universe of PHP ignorance, the fact that it displays the correct number of values (i've checked several different nodes) seems to indicate that there's something going right... but I dunno...

nancydru’s picture

Let's merge your example that was getting the values with what I think is more logical. I need to try to set up a test site if this doesn't work. You might also do something like print_r $field_animals; and copy that here if this doesn't do it. BTW, it looks like $field_animals is an array of arrays.

  $animals = array();
  foreach ($field_animals as $value) {
    $animals[] = array($value);
  }
  echo implode2(', ', ', and ', $animals);

Nancy W.
Drupal Cookbook (for New Drupallers)
Adding Hidden Design or How To notes in your database

joeboris’s picture

It still displays "Array, Array, Array and Array", I'm afraid.. I've been trying out a lot of combinations, but all I can get is the "Array..." result or the "Rabbit and Rabbit" result...

nancydru’s picture

Please explain to me how you set this field up and with which modules so I can create a test environment.

Nancy W.
Drupal Cookbook (for New Drupallers)
Adding Hidden Design or How To notes in your database

joeboris’s picture

I've used

CCK text field, check-boxes with multiple choice enabled (required field), plain text with the choices filled into the Allowed values list box
Contemplate for styling

...so it's pretty straight forward...

The field is a part of my profile-page, which also has a lot of other features (also in the contemplate... template)... So if there are any collisions with other modules or stuff in the contemplate, I guess I'm pretty much on my own.

For reference, this is the tutorial I used to make the user-profile...

nancydru’s picture

I find that tutorial anything but straight forward. But I just emailed Michelle and asked her to look at this thread.

Nancy W.
Drupal Cookbook (for New Drupallers)
Adding Hidden Design or How To notes in your database

michelle’s picture

I looked through this thread and it the problem really doesn't have anything to do with the tutorial since what the OP is doing isn't part of the tutorial at all. The tutorial is pretty straight forward as long as you're doing the same thing I did. It's customizing it that trips people up. I guess it's like a recipe... You can change the ingredients if you want, but you'd better know how to cook if you're going to deviate from the recipe. ;)

At any rate, this isn't something I can help with. I don't know PHP that well and arrays still make my head spin. Plus I'm very sick and not able to think all that clearly. So, sorry, but nothing I can do. :(

Michelle

--------------------------------------
My site: http://shellmultimedia.com

nancydru’s picture

Thanks, Michelle. It's getting close to time...

joeboris’s picture

I was thinking of the text-field + contemplate combination, with regards to the straight-forwardness...

...as far as I can see, it's the cck field that's storing the data, and the contemplate template which shows it (if all goes well), I just thought I'd reference the tutorial, in case there were some conflicts obvious to someone other than me...

So the only modules I can think of with direct relevance to this issue are cck (text field) and contemplate, and how the data in the text field can be retrieved and outputted though contemplate....

nancydru’s picture

Try doing a print_r $field_animals; and let's see what it looks like.

Nancy W.
Drupal Cookbook (for New Drupallers)
Adding Hidden Design or How To notes in your database

joeboris’s picture

<?php print_r($field_animals); ?>

Makes this:

Array ( [0] => Array ( [value] => Dog [view] => Dog) [1] => Array ( [value] => Cat [view] => Cat ) [2] => Array ( [value] => Hamster [view] => Hamster ) [3] => Array ( [value] => Rabbit [view] => Rabbit) )

So, it looks like an array of arrays, yes.. (yes?)

nancydru’s picture

  $animals = array();
  foreach ($field_animals as $key =>$value) {
    $animals[] = $value['value'];
  }
  echo implode2(', ', ', and ', $animals);

Nancy W.
Drupal Cookbook (for New Drupallers)
Adding Hidden Design or How To notes in your database

joeboris’s picture

It works perfectly! I really have to thank you so much for the time and effort you have put into this, Nancy! It's really very, very nice of you, and I appreciate it very, very much! Thank you!!

nancydru’s picture

I'm glad it's working. One of these days, I'll get more familiar with CCK and Contemplate; unfortunately, paying work has to come before pro-bono fun stuff.

Nancy W.
Drupal Cookbook (for New Drupallers)
Adding Hidden Design or How To notes in your database

sza’s picture

If it helps somebody, below is the code which solves this problem:

  1. you need to rewrite content.css value in your theme:
    .field .field-label-inline {
      visibility:visible;
    }
    
  2. Follow readme instructions in cck/theme, create your field.tpl.php and insert there this code:
    <?php if (!$field_empty) : ?>
    <div class="field field-type-<?php print $field_type_css ?> field-<?php print $field_name_css ?>">
      <?php if ($label_display == 'above') : ?>
        <div class="field-label"><?php print $label ?>:&nbsp;</div>
      <?php endif;?>
      <div class="field-items">
        <?php $buffarray = array();
               foreach ($items as $delta => $item) :
                if (!empty($item['view']) || $item['view'] === "0") : 
                  $buffarray[] = $item['view'];
                    if ($delta == count($items) - 1) { ?>
                      <div class="field-item">
                        <?php if ($label_display == 'inline') { ?>
                          <div class="field-label-inline"><?php print $label ?>:&nbsp;</div>
                        <?php }
                        if (count($buffarray) > 1) { print implode(', ', $buffarray); } else {
                          print $buffarray[0]; 
                        } ?>
                      </div>
                    <?php } ?> 
          <?php endif;
              endforeach;?>
      </div>
    </div>
    <?php endif; ?>
    

Results:

  1. "Inline" mode -
    Animals: Dog, Cat, Hamster, Rabbit
  2. "Above" mode -
    Animals:
    Dog, Cat, Hamster, Rabbit
nancydru’s picture

Great.

BTW, print implode(', ', $buffarray) will produce the same thing as print $buffarray[0] if there is only one item, so the "if" is unnecessary.

Nancy W.
Drupal Cookbook (for New Drupallers)
Adding Hidden Design or How To notes in your database

sza’s picture

I agree :)

But when I type this code, I thought that this variant will be more optimal, because it will be less of hits function "implode".
Although I do not know how it really happens :)

JConnell’s picture

Thank you very much sza, this worked great!

hunterchristy’s picture

this works great in the regular node, but how would one do it in views?

loginsvariaditos’s picture

If tried to do it your way, but finally i tried to return to the basics (i had some problems with the implode2 function). I hope it can also help you.

<?php
$puntuacion = "";
$i = 0;
foreach ((array)$field_proyectos_otrosmiembros as $item) { 
$i = $i+1;
if ($i < count($field_proyectos_otrosmiembros)) { $puntuacion = ", "; } else { $puntuacion = ". "; }
print $item['view'].''.$puntuacion.' ';
}; 
?>

Thanks u all for the help in the forum!

philingle’s picture

This last way worked for me too. I had failures due to the implode2 function as well.

One thing about this last one is that it get a space after my words and before the punctuation, and cant work out how to get rid of it.

nancydru’s picture

I doubt your array is big enough to make a difference, but the code could be much more efficient:

<?php
  $puntuacion = "";
  $i = 0;
  $max = count($field_proyectos_otrosmiembros);
  foreach ($field_proyectos_otrosmiembros as $item) {
    $puntuacion = (++$i < $max) ? ", " : $puntuacion = ". ";
    print $item['view'].''.$puntuacion.' ';
};
?>

This should run quite a bit faster.

Rameez’s picture

How to implement it in Drupal 6?

Following is the present code in content-field-tpl.php

<?php if (!$field_empty) : ?>
<div class="field field-type-<?php print $field_type_css ?> field-<?php print $field_name_css ?>">
  <?php if ($label_display == 'above') : ?>
    <div class="field-label"><?php print t($label) ?>:&nbsp;</div>
  <?php endif;?>
  <div class="field-items">
    <?php $count = 1;
    foreach ($items as $delta => $item) :
      if (!$item['empty']) : ?>
        <div class="field-item <?php print ($count % 2 ? 'odd' : 'even') ?>">
          <?php if ($label_display == 'inline') { ?>
            <div class="field-label-inline<?php print($delta ? '' : '-first')?>">
              <?php print t($label) ?>:&nbsp;</div>
          <?php } ?>
          <?php print $item['view'] ?>
        </div>
      <?php $count++;
      endif;
    endforeach;?>
  </div>
</div>
<?php endif; ?>
Junro’s picture

NancyDru code is perfect :) thanks

Rameez’s picture

HI,
Thanks a lot for help, but can you please tell me where to put this code?

I tried to replace it in content-field-tpl.php, but didn't worked for me. Please explain bit in detail?

Junro’s picture

See #758558: Display multiple cck field values in Single line.

Don't write things twice please.... First the post, and after, if no answer with post, try the issue :)

zeta1600’s picture

NancyDru, this worked very well. Can you help on a similar situation. I would like to have an "and" prior to the last item, and if there are more than a first item and last, it would be separated by a comma. For example.
2 items: Alpha and Beta
3 items or more: Alpha, Beta and Gamma.

Thanks in advance.

nancydru’s picture

  $num_authors = count($authors);
  if ($num_authors < 1) {
    $author_list = NULL;
  }
  else {
    if ($num_authors == 1) {
      $author_list = $authors[0];
    }
    else {
      $last = array_pop($authors);
      $author_list = implode(', ', $authors) . ' and ' . $last;
    }
  }
zeta1600’s picture

I wish I knew how to code.

nancydru’s picture

I didn't know PHP when I started doing Drupal (many other languages though). I needed to do something for which there was no module, so a friend gave me a sample module outline and I started looking at other code. After a lot of cut-and-pasting, my code actually worked. Another resource for you: http://php.net - the online PHP manual.

hoff331’s picture

Nancy,

I am trying to achieve the same comma separated results (minus the "and") as all previous posts. I am working in Drupal 7 with a custom node.tpl file. My code is as follows:

  <?php if (!$page): ?>
    <h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?></a></h2>
  <?php endif; ?>
  
  <div class="project-teaser-view">
      <div class="top">
		  <?php print render($content['field_project_image']); ?>
          <p>
          <span>Client: </span><?php print render($content['field_project_company']); ?><br/>
          <span>Website: </span><?php print render($content['field_project_website']); ?><br/>
          <span>Project Type: </span><?php print render($content['field_project_type']); ?><br/>
          <span>Project Status: </span><?php print render($content['field_project_status']); ?>
          </p>
      </div>
      <div class="bottom">
      	<?php print render($content['body']); ?>
      </div>
  </div>

  <?php print render($content['links']); ?>

  <?php print render($content['comments']); ?>

The field ($content['field_project_type']) is a Checkbox/Radio button list(Text). There are only 3 values, but I would like a comma placed between them when multiples are selected. How can I do this?

PS.

Doesn't this seem like an option that should be included in Drupal 7 by default? It is included in views under Multiple Field Settings.

hoff331’s picture

http://drupal.org/project/textformatter

This does exactly what we have been asking for!

subir_ghosh’s picture

Phew! Finally!

Thanks for the snippet :)

-----------------------------
Subir Ghosh
www.subirghosh.in