Question:

How to redirect user to login page when anonymous user click on the flag link?

Brooklyn: 5 days ago

Redirect user to login page when anonymous user click on the flag link.

How to achive this?

I have created flag links by

   function MYMODULE_preprocess_node(&$variables) {
 $node = $variables['elements']['#node'];
  $flag_link_service = \Drupal::service('flag.link_builder');
$flag_link = $flag_link_service->build($node->getEntityTypeId(), $node->id(), 'YOUR_FLAG_MACHINE_NAME');
$variables['flag_link'] = $flag_link;
}

Placed variable in twig template.

I want to do something like

 If ($user->uid) == 0)
 {
redirect to login
 {
 else
 {
   {{ flag_link }}
   }

Answer:
Charlie: 5 days ago

I have handled this by only showing the flag element when the user is logged in. When the user is not logged in, I have rendered out the flag graphic (eg, the heart) as a link to 'user/login?destination=whatever'. This eliminates the need to alter the flag link, especially since it also typically has AJAX associated with it.