1

I've created a views template (based on views-view-field.tpl.php) because I want to exclude a certain value ('o') from being displayed. I came up with the following code:

$data = $row->field_my_field;
$raw_value = $data[0]['raw']['value'];
$rendered_value = $data[0]['rendered']['#markup'];

if ($raw_value == 'o') {
}
else {
  print $rendered_value;
}

This works fine for a single value, but this field allows for multiple values (up to about 20). How can I modify the code to print all of the values except, if present, 'o'?

6
  • 1
    I think I must be missing something here, but what's to stop you looping through $row->field_my_field and doing whatever you want?
    – Andy
    Jul 31, 2012 at 11:59
  • Extreme lack of knowledge of PHP. My talent is generating content, not coding. Jul 31, 2012 at 12:48
  • Gotcha. And if a field has an 'o' at delta 3, should the entire field be hidden, or just delta 3?
    – Andy
    Jul 31, 2012 at 12:53
  • Just delta 3; I want to display all values except 'o' for the given field_my_field. Jul 31, 2012 at 12:59
  • Does it only make sense to have the 'o' omitted for the View, or might you also want the same effect when viewing a standalone entity (eg node)?
    – Andy
    Jul 31, 2012 at 14:26

1 Answer 1

1

You can do it in the template itself quite simply, something like:

<?php foreach ($row->field_my_field as $data): ?>

  <?php if ($data['raw']['value'] == 'o'): ?>
    // Output nothing, or placeholder, whatever
  <?php else: ?>
    <?php print $data['rendered']['#markup']; ?>
  <?php endif; ?>

<?php endforeach; ?>

This is a custom template for that particular field, and so should only be used with it (which can be done via preprocess). You might also need to be careful about the name of the field changing if the field's changed in the View.

The nicest approach I can think of is probably using hook_field_attach_view_alter():

function MYMODULE_field_attach_view_alter(&$output, $context) {

  $field_name = 'field_test';
  $to_hide = array('o');

  if (isset($output[$field_name]['#field_name'])) {
    if ($field_name == $output[$field_name]['#field_name']) {
      foreach ($output[$field_name]['#items'] as $delta => $item) {
        if (in_array($item['value'], $to_hide)) {
          unset($output[$field_name][$delta]);
        }
      }
    }
  }
}

That will work for Views and a normal entity view. AFAIK you can use $context to detect whether you're in a View or not, but I can't remember what you'd check for exactly. (And if you later find you do want to display the field like this outside of Views, it's painless to change.)

HTH

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.