In the course of working with Views, we often would like to provide conditional checks for display on a field per row. For example, imagine a directory site that allows users to opt out of displaying their address. In older implementations we’ve achieved this functionality through php in a field or in templates.
Fortunately, the current versions of Views include a quick solution with flexible implementation!
This solution requires that you have Views (Well, yeah.) and CCK (Always for D6, depends on method for D7)
For our directory example, the basic method is as follows:
- Add address field(s) to Content Type or Entity.
- Add control field (e.g. “Opt in”) to Content type or Entity.
- Create a View to display the content.
- Add the address field(s) to the view and mark “Do not display”
- Add the control field to the view and choose to rewrite.
- Add your address field(s) token(s) to the rewrite field.
- In “No Results Behavior,” select “Hide rewriting if empty” (Views 3)/“Do not rewrite if empty” (Views 2) and “Count the number 0 as empty.
- Done! (sorta...)
The trick is that your control field needs to return a value of ‘0’ if you want the content hidden.
In Drupal 6 the easiest path is to create an integer on the content type and choose “Single on/off checkbox” as the form element. You’ll need to specify allowed values of ‘0’ and ‘1’ and since this type of field doesn’t display a label it’s best to include a key|value pair for the ‘on’ value; for this example something like “1|Opt in” is probably best.
The above works in Drupal 7 so long as CCK is installed and enabled (to provide the “Single on/off checkbox” element), but the Entity system gives us some other options for providing the value. One quick example uses Taxonomy:
- Create a Vocabulary with two terms, "Hidden" and "Display"
- Create a new integer field for the Vocabulary.
- Assign the terms Titles that correspond with the values you want to provide, e.g. “Hidden” has a ‘Value’ of ‘0’ and “Display” has a Value of ‘1’.
- Create a new taxonomy field on the entity containing the field you want to display.
- Create the basic view as above.
- Instead of adding the control field directly, you'll first need to add a relationship to the taxonomy field you added to the entity.
- Now add the integer field with the relationship set.
- Setup the rewrite on the integer field.
This type of solution is a little trickier to set up in views, but it's great if you want to require the user to make a conscious choice because we can make selecting a term required to submit the content without a default behavior (unlike the Single on/off checkbox).
This is just a basic little trick that we stumbled across recently and we hope it’ll be useful for someone else. If it helped solve a problem you’re finding or you’ve got a particularly rad implementation, let us know in the comments below!