0

I have a taxonomy reference field that allows for multiple values.

In Views, when displaying this field, I have configured it as follows:

enter image description here

I was wondering if it's possible to somehow configure Views to make this output grammatically:

EXAMPLE 1

  • Field label: I like:
  • Values in node: apples, bananas
  • Views current output: I like apples, bananas.
  • Desired output: I like apples and bananas.

EXAMPLE 2

  • Field label: I like:
  • Values in node: apples, bananas, pears
  • Views current output: I like apples, bananas, pears.
  • Desired output: I like apples, bananas, and pears.

1 Answer 1

1

I did this in D6 using a CCK field formatter and using the Multiple Group Values.

What you want to do is inform Drupal essentially of a new radio option for "Display Type" that formats the output how you want for the collection of elements.

Again my solution is for D6, but you basically make a field formatter in D7 as well ...

# expose the formatter to ckk using a hook
function MYMODULE_field_formatter_info() {
  return array(
    'compressed_days_formatter' => array(
      'label' => t('Compressed Days'),
      'field types' => array('date', 'datestamp', 'datetime'),
      'description' => t('Displays a listing of days in a month with commas'),
      'multiple values' => CONTENT_HANDLE_MODULE,
    ),
  );
}

# define our theme function
# this turns array('2011-12-03', '2011-12-04', '2011-12-05')
# into say "december 03,04,05 2011".
# and stradles months / years OK by outputting multiple lines.
function theme_formatter_compressed_days_formatter($elements) {
  $output = array();
  foreach (element_children($elements) as $k) {
    $day = $elements[$k]['#item']['value'];
    $ts = strtotime($day);
    $Y = date('Y', $ts);
    $M = date('M', $ts);
    $d = date('d', $ts);
    $dates[$Y][$M][]=$d;
  }
  foreach ($dates as $year => $months) {
    foreach ($months as $month => $days) {
      $output []= $month.' '.implode(', ',$days).', '.$year;
    }
  }
  return implode('<br>',$output);
}

So I haven't done this in D7 (yet) ... but the approach would be the same. You'd just implode most of your elements with commas, and then the last item you tack on your 'and' as-needed.

A hacky-er way to do this is probably with an alter hook in views_pre_render() that examines each result and looks for the last comma and replaces it with an "and". That would work but its more cryptic and sloppy ... I think you really want a formatter here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.