How can I change the output of a field in a View based on a conditional PHP statement? For example,

  if ($field_contents == "red") {
    $field_output == "This field is red";
  }
  else {
    $field_output == "This field is not red";
  }

I'm sure I've seen this before, but I can't work out how to do it now.

Comments

dawehner’s picture

You can do this via theming, or preprocess.

Theming is easy:
Choose a template suggestion which fits to your needs, and there write this php. And do a print at the end.

I guess you should replace $field_output with $output.

jim0203’s picture

Thanks! Ended up writing a new theme_views_view_field() function: in case anyone else stumbles upon this, it looked like this:

function mytheme_views_view_field($view, $field, $row) {
  if ($field->field == 'type' && $row->node_type == 'mynodetype') {
    return $row->node_title;
  }
  else {
  return $field->advanced_render($row);
  }
}

This means that whenever a view displays a node type field for a node with type 'mynodetype', it will display the title of that node rather than its type.

dawehner’s picture

Status: Active » Fixed

Fine. Do you want to write documentation about how to theme it?

jim0203’s picture

Sure, seems like a good way to give something back to the community. Where should I put the documentation? Is there any style guide to follow?

dawehner’s picture

Status: Fixed » Active

There are many ways:
1. write a blog entry
2. write a d.o handbook
3. Write a description in the help of views. See the folder /help in views. Add a file with the documentation, and upload it here. Then i would create a patch for you, if you don't want to do it yourself.

jim0203’s picture

I've had a look through views/help and there doesn't seem to be a natural place for this piece of documentation; similarly, it's just a standard intercept and override once you know what function you're after and that Views doesn't let you do this sort of thing in the UI, so a d.o handbook doesn't seem quite right.

I've written a blog post, though, which assumes minimal knowledge of themeable functions:

http://state68.com/content/using-themable-functions-control-output-view

If anyone wants to take anything from there and use it in a handbook or in the official Views help then that's cool with me.

merlinofchaos’s picture

Status: Active » Fixed

Status: Fixed » Closed (fixed)

Automatically closed -- issue fixed for 2 weeks with no activity.