2

I want to create a view of flaggings and show content from the flagged entity.

However, on a flaggings view (Flag 4.x, Drupal 8/9), when I try to add a relationship, I can only add a relationship to the User, not the flagged entity.

Is this functionality not available in Flag?

When I create a view of nodes and want to pull in the flags, all I have to do is add a relationship to the Flag and it pulls in the flaggings automatically. So the Flag module supports going from nodes to flaggings, but how do I go from a view of flaggings to the flagged nodes?

Why I am trying to do this

Normally, I would just go from nodes to flaggings. However, this time, I have three different flags, and the same node may be flagged by multiple flags, and I want to show an entry for the node for each flagging, not one entry for the node for all flaggings.

0

1 Answer 1

2

Whoops, this is a work in progress to be added to Flag at some point.

In the meantime, this can be worked around using an entity reference field.

First, add an entity reference field to the flag.

Next, set the entity reference using hook_flagging_presave().

function MYMODULE_flagging_presave(FlaggingInterface $flagging) {
  switch ($flagging->getFlagId()) {
    case 'MYFLAGTYPE':
      if ($flagging->isNew()) {
        // Set entity reference for new flaggings.
        $flagged_entity_id = $flagging->get('entity_id')->value;
        $flagging->set('field_myflag_entityreference', $flagged_entity_id);
      }
    break;
  }
}

Finally, you can use the entity reference to the flagged node in your view in the same way as any other entity reference.

Because the flag module patch to solve this issue is in flux, it seems to me a bit dangerous to apply the patch to a production site, because the ultimate direction of the flag module may differ from any given patch. So, using an entity reference has the advantage of achieving the desired solution now (get access to the flagged entity in the flaggings view) while still allowing the future flag solution to be used (when flag becomes able to support this, you can simply delete the entity reference field, as it will no longer be necessary).

0

Your Answer

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

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