How to add a Flag link to a Drupal View
Update 9/2/13: It's been brought to our attention that this is now possible via the latest version of flag + views without the method described below.
The Flag module is really quite cool. It allows you to define a series of flags and tie them to all nodes of a particular content type (or types). So an example might be giving your users the ability to “flag” content as inappropriate. The flag can either be defined on a user level, or even a global level (the entire page is either marked just for that user, in which case you could see how many users flagged a particular page, or it can be flagged once by anyone, and it’s either flagged or not flagged).
Another example might be a node of type Contact, which keeps track of your new company leads. You could make a flag that would determine if a Contact node has been contacted by your staff yet.
For a client, we were tasked with setting something up along the lines of the second example. The client wanted to be able to see all Contacts that hadn’t yet been contacted. And also all contacts that had. The idea was that staff could use a View of all uncontacted nodes, contact them, then flag them as contacted.
So here’s how we did it (in Drupal 7):
- Install the Views PHP module and enable it. This will allow you to embed php into a view cell.
- Add a new nid/node id field to your View. Make sure to check the “Exclude from display” checkbox.
- Rearrange your fields so that your hidden nid field is at the top of all fields. This is important. It needs to be “available” as an element to the custom php field we are about to add, and if it’s after, the custom php field won’t see it.
- Add a new Global: PHP field.
- add the following code to the Output Code section of the field (in php): print flag_create_link("the_machine_name_of_your_flag", $row->nid);
- Click the apply button
And you’re set! That’s all that’s needed. You now have a flag/unflag link on your view. You may of course want to add other fields like Title, etc…, but that’s up to your application.
For more information, see the video below!