I have a Drupal 8 site with the Flag module.

I want when a user creates or updates a node, product, store, group, ... the updated entity is flagged.

How to flag an entity when it is created or updated ?

I'm testing the "Rules" module which is finally (usable) in production.

But how do you flag down a new entity when it is created ?

What should be put in "Action", because it is no longer like in Drual 7 with an interface.

enter image description here

enter image description here

  • Have you looked into the Rules module?
    – bleen
    Sep 10 '20 at 19:31
  • Might this be a duplicate of: drupal.stackexchange.com/questions/2076/…
    – bleen
    Sep 10 '20 at 19:32
  • 1
    @bleen Yes, but the Rules module seems completely dead, it's been years since there is a stable version and I don't dare install it on my non-production site.
    – sdfff
    Sep 10 '20 at 20:24
  • @bleen Can the "Actions" module do this ?
    – sdfff
    Sep 10 '20 at 20:29
  • @sdiff your statement is completely false and misleading - Rules is extremely active and under development, and is even compatible with D9 and is used by tens of thousands of sites. This posters task is trivial with Rules.
    – anonymous
    Sep 10 '20 at 22:37

You can use HOOK_entity_presave to trigger when node gets created. I updated code for you. Make sure that you change the capital letters to correct values.

function MODULENAME_entity_update(Drupal\Core\Entity\EntityInterface $entity) {
  // Check which content type would you like to flag.
  // You can use https://www.php.net/manual/en/function.in-array.php to check for 
  // multiple content types
  if (in_array($entity->bundle(), ['mycontentype1', 'mycontentype2'])) {
    $flag_id = 'yourflagname';
    $flag_service = \Drupal::service('flag');
    $flag = $flag_service->getFlagById($flag_id);
    // Flag an entity with a specific flag.
    // https://www.drupal.org/docs/drupal-apis/entity-api/introduction-to-entity-api-in-drupal-8
    $flag_service->flag($flag, $entity);
  • Thanks, but I'll try to do this from the Drupal 8 interface.
    – sdfff
    Sep 10 '20 at 23:22
  • I don't know programming very well. I know how to create the base of a module, but what should the module file contain ?
    – sdfff
    Sep 12 '20 at 15:16
  • @sdfff I updated the code for you.
    – Ales
    Sep 12 '20 at 16:00
  • Thanks, I just created a module with your code, but I have 2 PHP error when I register a node ibb.co/2q8YgXp ibb.co/fGwxXGx ibb.co/4dWRpJr
    – sdfff
    Sep 12 '20 at 17:24
  • is the content already flagged? than maybe need to add another check
    – Ales
    Sep 12 '20 at 17:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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