Cannot programmatically flag a node for anonymous users

Created on 30 November 2022, about 2 years ago
Updated 19 October 2024, about 2 months ago

Problem/Motivation

hi, i have a controller in which i have this code:

public function redirection($id)
{
$langage_routing = '';
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
if ($language != 'de') {
$langage_routing = '/' . $language;
}
$flag_id = 'flag_machine_name';

$flag_service = \Drupal::service('flag');
$flag = $flag_service->getFlagById($flag_id);
$entity = Node::load($id);
try {
// saving flag to cart
$flag_service->flag($flag, $entity);
$flag->save();
$response = new RedirectResponse($langage_routing . '/en/inquiry-list');

$request = \Drupal::request();
// Save the session so things like messages get saved.
$request->getSession()->save();
$response->prepare($request);
// Make sure to trigger kernel events.
\Drupal::service('kernel')->terminate($request, $response);

return $response->send();

} catch (\Throwable $th) {

$response = new RedirectResponse($langage_routing . '/en/inquiry-list');
return $response->send();

}
}

So, the way it should work is that when a user visits this route than the node with that id should be flagged. The above code works perfectly for authenticated users, but not for anonymous users. For anonymous users it sometimes works and sometimes doesn't, sometimes the node is correctly flagged and other times is not. Another issue with anonymous users is that sometimes flag nodes from other anonymous users shows to me.

Doing some debugging i observed that node is only correctly flagged when a session id is created for the anonymous user, i thought adding this code will resolve the session id issue for anonymous user but unfortunately it didn't:

$request = \Drupal::request();
// Save the session so things like messages get saved.
$request->getSession()->save();
$response->prepare($request);
// Make sure to trigger kernel events.
\Drupal::service('kernel')->terminate($request, $response);

so any help will be welcomed, thanks.

Steps to reproduce

Proposed resolution

Remaining tasks

User interface changes

API changes

Data model changes

💬 Support request
Status

Active

Component

Flag Bookmark

Created by

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024