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.