I created a module for flagging entities automatically when created or updated.

There are some errors in my code because only nodes work.

If a user "user1" creates a node, the flag will be in his name. I want the flag to be done automatically on behalf of the site administrator.

How do I get the administrator to automatically flag?

use Drupal\flag\FlaggingInterface;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\user\Entity\User;
use Drupal\commerce_store\Entity\Store;
use Drupal\commerce_product\Entity\Product;
use Drupal\group\Entity\Group;
use Drupal\node\Entity\Node;
use Drupal\comment\Entity\Comment;

 * Flag node.
function admin_task_notify_node_update(Node $node) {
    $flag_id = 'moderate_node';
    $flag_service = \Drupal::service('flag');
    $flag = $flag_service->getFlagById($flag_id);
    $flag_service->flag($flag, $node);

1 Answer 1


FlagServiceInterface::flag takes an $account argument:

The account of the user flagging the entity. If not given, the current user is used.

So for example:

$flag_id = 'moderate_node';
$flag_service = \Drupal::service('flag');
$flag = $flag_service->getFlagById($flag_id);
$account = \Drupal\user\Entity\User::load(1);
$flag_service->flag($flag, $node, $account);
  • Thanks, but I have a PHP error. I updated my question.
    – sdfff
    Commented Sep 17, 2020 at 19:57
  • Check the arguments, you have them the wrong way round
    – Clive
    Commented Sep 17, 2020 at 20:34
  • Thanks, it works. But how do I do for the "Flag User" part? Do I add $account twice
    – sdfff
    Commented Sep 17, 2020 at 20:54
  • Just name the variables differently - use $admin_account for the admin account for example
    – Clive
    Commented Sep 17, 2020 at 22:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.