Some background: I'm new to Drupal 8/9 module building. I need a particular content type's nodes to be automatically flagged. I have this working using the code below. However, the flag involved also has a custom field I need to set.

  • It's an entity reference field (to another node)
  • I want to set the flag's custom entity reference field to be the same value as an entity reference field on the flagged node.

(This may seem like a strange thing to do. There may be a better way to accomplish the UX goals. I still want to know how to do it.)

'rf_tweaks' is the module machine name, 'research_note' is the node content type, and 'research_item' is the name of the flag.

use Drupal\node\Entity\Node;

function rf_tweaks_node_insert(Node $node) {
  if ($node->bundle() == 'research_note'){
 $flag = \Drupal::entityTypeManager()->getStorage('flag')->load('research_item');
 \Drupal::service('flag')->flag($flag, $node);

There's some great info at the flag api page, but the methods are different enough that it's not clear to me how to adapt them to this situation.

1 Answer 1


The method in your last line of code returns the "flagging" entity, which represents the entity/flag relationship. That's the thing you need to set the field on. e.g.

$flag = \Drupal::entityTypeManager()->getStorage('flag')->load('research_item');
$flagging = \Drupal::service('flag')->flag($flag, $node);

$flagging->field_foo->target_id = $node->field_bar->target_id;

That does involve the flagging entity being saved twice, so if performance ever becomes an issue you might need to create a Flagging entity manually and save it to avoid the double-hit.

  • Working for me. Much appreciated!
    – aharown07
    Commented Dec 7, 2021 at 23:14
  • I added commented code to try to understand what's happening... for my own education mostly. Two questions: 1. Do I have it about right? 2. We use ->save() to add the field value, rather than using the flag service because using the service would crate another flagging instead of altering the current one?
    – aharown07
    Commented Dec 9, 2021 at 15:36

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.