Creating Following and Followers Tabs With Flags in Drupal 7
I’m writing this post because I’ve been using Drupal to rapidly-prototype an MVP (and I have many, many thoughts on Drupal, but I won’t get into them here). One of the features was to have a list of followers (who follow a user) and a list of the users that a certain users follows, which is a very typical setup. I’m writing this post because I had one hell of a time putting this thing together in Drupal 7, and I’m hoping it will save someone else from going through the pain I went through.
First, let’s rubber duck and clearly define our requirements for the two lists.
Following: A list of users that a specific user has flagged ‘follow’. In other words, a list of users flagged by another user. Followers: A list of the users that have flagged a specific user to ‘follow’. In other words, a list of users that have flagged another user.
I’m using the terminology flag here since we’ll be using the flag module to put together the following/followers functionality. The two modules we’ll need are:
First, you’re going to need to create a new flag for ‘follow’. Setting up a new flag is fairly trivial, and I called my flag ‘follow_user’ and set it to be a global flag.
Now, create a new view for Followers. You’re going to need to set the following options:
- Title (very important, but just for you)
- Path: /user/%/followers (or anything you’d like, as long as the % is in there)
- Contextual Filter: User(uid) (this is to grab the uid out of the % in the path)
- Set the Contextual Filter above to ‘do not use a relationship’. This step is important
- Create a ‘Flags: User Flag’ relationship for any user (not just the current user)
- Create a ‘Flag: User’ relationship to grab the user data from the above relationship. (the relationship drop down should reference the flag created in the step above)
- Create a ‘User:Name’ field that uses the above relationship
And that’s how you do the followers tab. For the following tab, create another view, with basically the same parameters (the path and will be different, obvs), but the major differenct is with the Contextual Filter:
- Make sure the contextual filter is referencing the Flag User relationship (you may need to set up the relationships first, then add the Contextual Filter).
- Also make sure that the ‘User:Name’ field does not reference the relationshp (or else it will just repeat the name of the current user you are viewing).
For reference sake, here is what the views look like in my admin:
Followers
Following
Hope this helps someone!