Score:0

How do I programmatically set a flag's custom entity reference field when programmatically setting the flag?

pe flag

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.

Score:1
cn flag

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;
$flagging->save();

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.

pe flag
Working for me. Much appreciated!
pe flag
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?
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.