Flagging and unflagging content is usually done by clicking links. These links are known as "flag links".

The Flag module puts these links for you — for your users — in certain places. For example, for nodes, links are shown beneath the node body in the area where all other node links are usually shown (e.g., beside the "Add new comment" link).

Sometimes this doesn't suit you.

Sometimes this doesn't work in the specific theme you use.

Sometimes you just realized there's no native way to put a flag in a view.

Sometimes you want to place the link in quite a different place.

In these cases, you'll want to place the link manually on the page.

To do this, follow two steps:

  1. Locate the template file in your theme directory (siteroot/sites/all/themes/mytheme) where you want to put the link (e.g. 'node.tpl.php' or 'user-profile.tpl.php'), and add to it a call to flag_create_link, as described below, in "Using flag_create_link()".
  2. If all works to your liking, instruct the Flag module to not show its own link. (This step is optional: it's possible to have two or more identical flag links on a page.) Do this by going to the flag edit screen and ticking off all the checkboxes in the "Display options" section.

Using flag_create_link()

Once you tell the Flag module not to print the flag links, the responsibility for printing these links falls on your shoulders. Don't worry, it's easy. You need to call flag_create_link() from your template file(s). This function gets two arguments: the flag name, and the ID of the object to flag. Note: By "flag name" we mean the flag's machine-name (as appears on its settings page).

Example 1

For nodes

<?php print flag_create_link('bookmarks', $node->nid); ?>
(Put this, for example, in 'node.tpl.php'.)

For comments

<?php print flag_create_link('my_comments', $comment->cid); ?>
(Put this, for example, in 'comment.tpl.php'.)

For paragraph items:

<?php print flag_create_link('paragraph_flag_name', $paragraphs_item->item_id); ?>
(Put this, for example, in 'paragraphs-item.tpl.php'.)

For users

<?php print flag_create_link('my_lovers', $node->uid); ?>
(Put this, for example, in 'node.tpl.php'; $node->uid stands for the node's author.).

In the above example, 'my_lovers' is the name of an existing user flag. You can't flag users using a node flag (and vice versa).

Example 2: For users

Drupal 6

<?php print flag_create_link('fools', $account->uid); ?>

Drupal 7

<?php
  $account = menu_get_object('user');
  print flag_create_link('fools', $account->uid);
?>

Drupal 8+

See flag.module file function flag_entity_view()

$build['follow_name'] = [
        '#lazy_builder' => [
          'flag.link_builder:build',
          [
            $entity->getEntityTypeId(),
            $entity->id(),
            'flag_name',
          ],
        ],
        '#create_placeholder' => TRUE,
      ];

Equivalent without using #lazy_builder:

$build['follow_name'] = \Drupal::service('flag.link_builder')
  ->build($entity->getEntityTypeId(), $entity->id(), 'flag_name');

Where to put this?

There are several possibilities:

  • If you're using standard Drupal profile pages, put this, for example, in 'user-profile.tpl.php'; $account->uid stand for the user whose profile page is being viewed.
  • If you're using the Content Profile module, put this, for example, in 'content_profile-display-view.tpl.php' but change $account->uid to $uid.

Troubleshooting

A problem you're likely to encounter is that the link doesn't show. Here are some steps that will guide you in solving the problem:

  • Are you editing the right template file? Type "blah blah" into your template and see if it shows up in your browser.
  • Calling flag_create_link() doesn't skip the flag's permission checks. Your link will never show up if the module's default link doesn't show up either. Make sure you associate the flag with the node type you are working with. And make sure the user browsing the page has permission to use this flag. In other words: before complaining "flag_create_link() doesn't work for me!", make sure the default link does work.
  • Under Flag access by content authorship- did you check the box for "Users may only flag content of others"? If you did, then you will not be able to see the flag of anything you authored.
  • Do the variables you're passing to flag_create_link() indeed exist in the template? It's easy to find out: place <?php print_r($variable_to_check); ?> in your template to see if some variable exist.
  • Calling flag_create_link() in 'page.tpl.php'? See the next section.

The 'page.tpl.php' problem (Drupal 6 only)

Note that a problem arises when putting the call to flag_create_link() in 'page.tpl.php'. At this late stage the JavaScript and CSS sections of the page (i.e., the $scripts and $styles variables) have been printed out already. So Flag's JavaScript (which enables AJAX links), whose inclusion is triggered by flag_create_link(), won't be included in the page.

This problem is specific to page.tpl.php under Drupal 6 (Drupal 7 doesn't have the problem). One solution is to put the call to flag_create_link() in a block instead. Here's another solution.

Comments

aurelien-bordeaux’s picture

Hi,
I tried using views to place flags on a page.
When creating a view, I don't find in the field list the flags I created.
I am using openpublish distro.

Anyone has an idea why? Or is it just not compliant with views?

Thanks

ethnovode’s picture

Hello,

You probably need to add a relation : flags in your view. Then you can add the flag link in your fields.

aurelien-bordeaux’s picture

Thanks for the tip! that worked out for me .

mtraherne’s picture

If there a way to add a flag summary into the node in code. (ie "12 users have flagged this node")?

I have done this in my summary view with one of the fields provided by the module, but ideally I would like to place this into the page itself.

Thanks.

Let this be a lesson to all those Drupal people out there. Read before you post comments!!!
How to add flag count to your node: http://drupal.org/node/305086#flag-counts

Rosamunda’s picture

<?php print flag_create_link('my_lovers', $node->uid); ?>
This is used to create a specific flag link.
Is there a way to show all flagging links, instead of adding them one by one?
Thanks!

tregismoreira’s picture

How to create a flag link in Views page? I'm using flag_create_link() but it don't working :/

bluesky_still’s picture

gabbariele’s picture

Hi there, I have the same issue. I guess the problem is that flag_create_link() needs a node id to work. If you just print out the node id, you'll find that a page generated from Views doesn't have a node id.
I've tried to find out if you can get the node id from the Views module, but that doesn't seem to be the right path to follow.

So, is it possibile that the flag link doesn't show out for some good reason we don't know?
How can we get the flag link appear with a page generated form a view of the Views Module?

Thanks

jmcoder’s picture

I'm creating a flag which is similar to the "bookmark" flag in that it associates a particular user with a particular content item.

Is there any way for me to add a flag allowing an admin to associate a particular with a particular nid in a certain flag? Sort of like allowing an admin to add a bookmark FOR a user - not letting the user add that bookmark by themselves. This is actually for designating leaders for a group - there is a group content type, and then I have a user flag which is used to flag nids of groups for which they are designated as leaders.

gravisrs’s picture

Is there an option to use CCK for the flag field ? Original functionality with just adding checkbox to node form doesn't work well with CCK related modules.

clockwood’s picture

I used this on my site and thought it might be useful to someone else.

Manually add comment flag:

<?php print flag_create_link('flag_name', $comment->cid); ?>
joshintosh’s picture

This is great, why isn't this included in the instructions above? That sure would have been nice.

da_twilight’s picture

I am having this rather strange problem. flag_create_link doesnt returns any html for a custom theme i made.. but works fine when switching to other default themes. On debugging it seems that the hook_theme isnt getting invoked for some reason. A print statement i placed in the flag_theme doesnt prints anything in mycustom theme but does goes invoked from other themes.

The strange thing is it used to work fine untill a few days back before i migrated to a new server. I might have made some unknown changes in the transition but have no clues what it is . Any suggestions on what i might have got wrong would be greatly appreciated.

Thanks.

bluesky_still’s picture

flag_create_link doesn't work in views views-view-fields--questions.tpl.php

I have a question list views,before I use flag_create_link() add a follow flag,it works well,
but someday,I want add another flag named bookmarks, use the same way ,but nothing output!
need help!

Anonymous’s picture

If you are for some strange reason needing to create this link in Panels while Context Keywords on enabled, the following code works:

print flag_create_link('bookmarks', %node:nid);

glitz’s picture

where does this code go? i have set up several flags for cck types. i then migrated them over to panels for formatting reasons, and i have all content listed the way i like except the "flag" link....i cant seem to find where, or how to add it back in??

thanks

glitz’s picture

nm got it thx

itserich’s picture

Could you share it?

Thanks!

bjsomers’s picture

I have the same issue and would like to know how you put a flag this link on the panel.

itserich’s picture

This thread should contain a file which works like a module. Might want to start at the bottom and work your way up.

http://drupal.org/node/332956

JoshuaBud’s picture

I simply added the code snippet to a panel pane using the 'New Custom Content' which is available when adding new content.

I've included a screenshot.

http://screencast.com/t/bQlrHmu55

Joshua Needham
(801)613-2778

JoshuaBud’s picture

I was trying the above example without success and then I found your comment http://drupal.org/node/295383#comment-3334516. It's working perfectly. Now to style the flag link to something other than text.

Joshua Needham
(801)613-2778

Stomper’s picture

I am getting errors when I try and view flagged nodes in my profile. I have cloned the original flag view but am using a custom flag for a node. What should the views relationships and views arguments be?

Error message:
________________
user warning: Column 'uid' in on clause is ambiguous query: SELECT COUNT(*) FROM (SELECT DISTINCT node.nid AS nid...
________________
The error repeats twice

Beneath the error it says "This user has not yet bookmarked any content." and I know that I have flagged two nodes (error repeats twice).

Help please

toddwshaffer’s picture

Brian, that was a bit of genius.

I was having an issue with getting a bookmark flag onto a panel page. After tinkering with multiple solutions I found this to be the most effective and wish I had seen this fifteen threads ago.

To clarify the solution:

This takes advantage of Context, Context Keywords and Flags to render the flagging links on Panel pages. Note: If you are using custom node templates instead of Panels this is not what you're looking for.

1) Install Context, Context Keywords and Flag (sudo drush dl flag context context_keywords)

2) Enable all modules (sudo drush enable flag context context_keywords)

3) Create a new panel on a page

4) Select "New Custom Content"

5) Copy/paste the code snippet from below:

<?php print flag_create_link('bookmarks', %node:nid); ?>
* Notice the %node:nid instead of $node->nid

6) Configure the input format to "PHP Code" (if you don't see that option available you will need to enable the php input formatter)

7) Ensure "Use Context Keywords" is enabled

8) Save/Update the panel, open up a node and look at the magic.

dreamcracker’s picture

Is it possible to put that code print flag_create_link('bookmarks', $node->nid); anywhere or only in the theme pages? Because i want that code in a module but if i put it in the module code and test it theres a alert box saying: "An HTTP error 404 occurred.
http://MYDOMAIN/flag/flag/bookmarks/?destination=node/9&token=uV1O-KznB5..."

is that my mistake?

Please help me and sorry for my bad english.

ngstigator’s picture

i tried creating a preprocessed template variable and it doesn't work. worked when i put it into the tpl file. hope this helps.

amsterdamdrupalnewbie’s picture

I have tried putting flag_create_link in my page-taxonomy.tpl file. I added the following code:

print flag_create_link('like', $tid);
but it gave:

An HTTP 404 error occurred
http://localhost/drupal/?q=flag/unflag&destination=taxonomy/term/74&toke...

I know nothing about coding so any help would be much appreciated. I am using drupal 7.9. I have also tried:

print flag_create_link('like', $term->tid);

and it gives the same result.

Ruriko’s picture

I want it to display as a drop down list showing all types of flags I made instead of a standard link. How can I do this?

carrierawks’s picture

I am looking for the same type of thing too. And I am using panels. None of the above tricks worked for me.

narcisgirona’s picture

How about using it in a block?

i added it however i'm getting an error:

print flag_create_link('bookmarks', $node->nid); 

Error:

Notice: Undefined index: regions a block_admin_configure_submit() (línia 496 de /home/example/public_html/modules/_block/block.admin.inc).
Warning: Invalid argument supplied for foreach() a block_admin_configure_submit() (línia 496 de /home/example/public_html/modules/_block/block.admin.inc).
Notice: Trying to get property of non-object a eval() (línia 30 de /home/example/public_html/modules/php/php.module(80) : eval()'d code).

Any ideas on how to show flag abuse link in blocks?

thanks

-Mania-’s picture

Blocks have trouble accessing the node so try loading it first.

<?php 
if ( arg(0) == 'node' && is_numeric(arg(1)) && ! arg(2) ) {
  $node = node_load(arg(1));
  print flag_create_link('bookmarks', $node->nid);
}
?>
jshenry’s picture

I got this to work using a global user flag in Drupal 7.

This will show the flag link anywhere and it works (no 404)

global $user;
print flag_create_link('service_status_normal', $user->uid); 

I'm by no means a php coder so I don't guarantee this for all setups!

tim.foxell’s picture

The $user array is the profile of the logged in user so the above code would generate the flag link to yourself, not the user profile you were viewing. Drupal 7 doesn't load the old D6 $account array so you need to generate it manually. See the following.

<?php
  $account = menu_get_object('user'); // Creates a user array based on the user profile you are viewing.
  print flag_create_link('user_flag', $account->uid); // Where user_flag is the name of the user flag you created.
?>

You can drop the "global $user;" all together from the above code unless you are doing a check to see if the logged in user is looking at their own profile.

drupalfan81’s picture

hi there! thanks for your post but I still can't get this working on Drupal 6. I am trying to show the User flag I created in a block on the user profile pages.

If I post this: print flag_create_link('follow_flag', $account->uid);
in my user-profile.tpl.php page it works just fine and displays the flag link on the user profile pages, but I want to post it in a block as you mentioned.

I have tried everything, but it doesn't seem to work.

I tried what you mentioned:

$account = menu_get_object('user');
print flag_create_link('follow_flag', $account->uid);

The link displays, but when you click on it, it shows an error: An HTTP error 404 occurred.
http://www.mysite.com/flag/flag/follow_flag/?destination=user%2F1&token=...

Any ideas on how I can get this flag to display and work in a block on D6. Thanks!!

deryck.henson’s picture

Using views to include the OPS (remove/add flag) link made it impossible to break it down and edit individual parts (link vs. text vs. whole package). For anyone else having as much trouble as I was at 6AM trying to use tokens to change the link to an image instead of text, here's a very simple thing to do:

1. Add the Flagging: Flag link field to the view and use whatever default display you want.
2. Make sure your custom image is on the server and your CSS file can reference it (as in, not in a private files directory with no permissions).
3. Add this to the CSS file of your choice:

a.flag.unflag-action {
content: url(../images/minus.png);
}

This keeps the link and gives you an image to click instead of the ugly text that probably didn't fit to begin with. The text will still show in the HTML but browsers will replace with the image.

BeaPower’s picture

Thanks, but this works only in Google Chrome, how about Firefox? Nvm, got it to work by using css for firefox!

vishy_singhal’s picture

Just curious - is there a easier way to show a number besides the flag button. For eg. if there are 20 users currently following a blog article, is there a way we can showcase that easily. If he/she chooses to unfollow, the corresponding number changes to 19.

vishy_singhal’s picture

I got it working. My bad, should have done my homework before posting this question.

drupalfan81’s picture

I have researched and tried everything without success on Drupal 6 in blocks.

It seems this does not work in Blocks...
print flag_create_link('fools', $account->uid);

The $account->uid value has nothing in it.

Even if I add this line:
$account = menu_get_object('user');

It doesn't seem to help. The only thing that does work is the

global $user;
$usersid = $user->uid;

But this is the logged in user. What I am trying to do is to display a block on all user profile pages and when you view another user's profile page while logged in as your user, you can click the flag to follow that user.

Can someone please tell me how to get the userid of the user's profile page my users are viewing?

Thanks!

drupalfan81’s picture

After an hour of failures and 2 minutes after posting this. I find the answer I was looking for. Gotta love how it always works that way...once you have given up...you have one last go and boom!

$account = user_load(arg(1));
print flag_create_link('follow_flag', $account->uid);

that's it!!

Bcwald’s picture

The D8 Module settings page links to this page, but there is no information on how to do this in D8.

TheDucksLover’s picture

I managed to display the link using the link_builder service of flag, but (in my case at least), the link simply refreshes the page and nothing is added to my bookmarks + no confirmation message is displayed :

btw I simply put this in a preprocess function..

$flag = \Drupal::service('flag.link_builder');
$flag_link = $flag->build($node->getEntityTypeId(), $node->id(), 'bookmark');
$variables['flag_link'] = $flag_link;

Where "bookmark" is the machine name of your flag, and $node-id(), the nid of your node.

DuneBL’s picture

I confirm that your code is nicely working!

asgorobets’s picture

While this code will work for the first time, it will probably be cached if render cache is enabled. Use lazy builders instead to avoid caching issues:

$flag_link = [
    '#lazy_builder' => ['flag.link_builder:build', [
      $user->getEntityTypeId(),
      $user->id(),
      'favorite_users',
    ]],
    '#create_placeholder' => TRUE,
  ];
mfgr’s picture

I'm sorry, novice here.... Where would I put this piece of code? I have a clean Drupal 8 install with Flag module (hopefully), but I'd like to put the bookmark link on the top of the page and not at the bottom....

Rick Bergmann’s picture

Incase you (or anyone else) are still looking for a solution, you put that code in a preprocess function (in my case I used preprocess_node) in your .theme file, then call it in the node.html.twig like {{ flag_link }}

The code that worked in my case:

Add to themename_preprocess_node()

$flag_link = [
  '#lazy_builder' => ['flag.link_builder:build', [
    $node->getEntityTypeId(),
    $node->id(),
    'favourites',
  ]],
   '#create_placeholder' => TRUE,
];
$variables['flag_link'] = $flag_link;

Add to node.html.twig:

{{ flag_link }}

Note "favourites" is the machine name of my flag, yours may be different.

tj2653’s picture

I added this to my .theme file:

function mytheme_preprocess_node(&$variables) {
$flag_link = [
'#lazy_builder' => ['flag.link_builder:build', [
$node->getEntityTypeId(),
$node->id(),
'myflagname',
]],
'#create_placeholder' => TRUE,
];
$variables['flag_link'] = $flag_link;
}

then tried to call it in my node.html.twig file using {{ flag_link }}, but I get the following error:

Fatal error: Call to a member function getEntityTypeId() on null in [mypath].theme on line 19

Any ideas what might be causing this?

Rick Bergmann’s picture

Yes, you need to replace the 'mytheme' part with the name of your theme.

tj2653’s picture

Thanks Rick, I should have mentioned I just changed it to "mytheme" for the post, since the original name was my site's name (not that it would be a terrible thing to post here). Sorry for the confusion :) Not defining $node was the issue, as TheDucksLover pointed out.

TheDucksLover’s picture

Rick Bergmann is right but I guess you already had changed "mytheme" to your real theme machine ID.

No, according to your error message, what's wrong is that $node is not defined. To get it, place $node = $variables['node']; before $flag_link = [ ...

It should work ;)

tj2653’s picture

Thank you very much TheDucksLover!! The issue was indeed $node not being defined. I'm just getting back into Drupal after quite a few years and wasn't the greatest coder to begin with :)

Azone’s picture

Is it possible to use this in the comment.tpl.php
print flag_create_link('bookmarks', $node->nid);

I want users to be able to flag/follow a node (ts in forum) but having the flag-link on the comment itself.

Drupal 7.50

Azone’s picture

I solved it by doing this in a code field for comments with DS-module:

$node = menu_get_object();
print flag_create_link('bookmarks', $node->nid); 

Idas’s picture

JavaScript toggle don't work. Drupal 7
Why?

mafzalzadeh’s picture

Does anybody know how Can I use Flag module to my twig theme on drupal 8?

alanpeart’s picture

Just an addition to the above instructions. My use case was that I wanted to generate the Flag link in a block in the sidebar, rather than displaying it using Twig. So you have to call render() in order to get the actual HTML. As in:

$status = [
	'#lazy_builder' => ['flag.link_builder:build', [
	$node->getEntityTypeId(),
	$node->id(),
	'your_flag_n',
	 ]],
	 '#create_placeholder' => TRUE,
];
$status = render($status);

You can then just echo this wherever you need it.

Technical Director at The Creative Coop

http://www.creative.coop

elgandoz’s picture

Thanks for that. Are you or somebody else able to indicate me how to print the flag count next to the link (with D8)? I want to reproduce the exact same display of "Follow this issue" in the above sidebar, with the count getting updated after a click. Thanks

Yanivs’s picture

It is possible to create a "Follow user" flag either manually (https://prkos.hr/User-Flags-Follow-Drupal-8) or by enabling the "Flag Follower" sub module which is part of the "Flag" module.

With this you can add a "Follow user" link on the user's account page ("/user/[uid]").

But, what if you are using the "Profile" module and you want to add the "Follow user" link to the user's profile page?

It is possible to do this with some changes to the link building code.

In your theme's theme_name.theme file, in hook_preprocess_profile() put:

function theme_name_preprocess_profile(&$variables){

  // Prepare "Follow this user" flag field.
  $flag_follow = [
    '#lazy_builder' => ['flag.link_builder:build', [
      'user',
      $profile->getOwnerId(),
      'following',
    ]],
   '#create_placeholder' => TRUE,
  ];
  $variables['flag_follow'] = $flag_follow;

}

Where:
theme_name - replace with the name of your theme

following - this is the default name the "Flag Follower" sub-module gives to this flag, if you create a flag manually replace this with the machine name of your flag

$flag_follow and flag_follow - this is the name you will later use in the profile twig template, you can replace it if you want

The arguments given to the link builder are:
- 'user' - this is the entity name of the entity you want to flag which in our case is a user

- $profile->getOwnerId() - because we want to flag a user we need to get the user id associated with the current profile (user id and profile id are not the same), so basically we are getting uid we want to flag

- 'following' - the machine name of our flag

After adding this piece of code you can use {{ flag_follow }} in your profile twig templates in order to print the "Follow user" link.

plousia’s picture

If like me you flail around a bit before getting this, here's a full example of manually adding a flag link to user.html.twig (Drupal 8 or 9).

In your theme's .theme file (replace THEMENAME with your theme's name and flag_machine_name with your flag's machine name):

function THEMENAME_preprocess_user(&$variables) {
  $user = $variables['user'];
  $flag_link = [
    '#lazy_builder' => [
      'flag.link_builder:build',
      [
        $user->getEntityTypeId(),
        $user->id(),
        'flag_machine_name',
      ],
    ],
    '#create_placeholder' => TRUE,
  ];
  $variables['flag_link'] = $flag_link;
}

In user.html.twig:

{{ flag_link }}
aharown07’s picture

@plousia Yes, I flail around quite a bit! Thanks for saving me some flailing.