Flag: Negotiate submitted flag form field value when flag()/unflag() is called from the flagging entity_type's hook_entity_update on the flagging.entity_type

Created on 30 October 2019, over 5 years ago
Updated 19 February 2025, 18 days ago

Given a flagging entity is configured for a given entity type, and its setting "Display checkbox on entity edit form" is checked
When flagging flag/unflag is invoked in a hook_ENTITY_TYPE_update (or hook_entity_update) for an entity of that type
Then the flag/unflag action happens as expected
And the Flag form edit field value for Flag is then immediately applied (potentially unsetting the expected flag action).

I don't know if this is the implementer/developer's responsibility to negotiate or if some option might be set in Flag.. But it sure threw me for a loop, so I thought I would open it for discussion. At the outset, I didn't see access to the submitted form (containing embedded Flag form) from within the main entity's update hook.

-Bronius

Original observations and story/notes/inquiry

Hi - I've loved Flag for years :) and finally have a really practical application for it!

Is there some reason that the same flag() operation works in code when run normally (ie. in a function or via `/devel/php`) but not when run within a hook_ENTITY_TYPE_update()?

$entity = \Drupal::entityTypeManager()->getStorage('my_entity')->load(2);
$flag_service = \Drupal::service('flag');
$flag = $flag_service->getFlagById('review_notification_queued');
$flag_service->flag($flag, $entity);

If I run the above in /devel/php I can see the db.flagging record created immediately after ->flag(), but when I invoke the same thing from a hook_.._update, I don't see any db record added nor error/log message. Yes, I've confirmed this is for an entity whose entity_id is not yet in the flagging table. And yes, I can watch it in the debugger: It is definitely getting to ->flag() in my entity's update hook.

It's the same with the unflag() operation. Here's with debugger running, down in the guts, I just watched this line from EntityBase::delete() pass:

$this->entityTypeManager()->getStorage($this->entityTypeId)->delete([$this->id() => $this]);

and confirmed valid and matching $this->id() and $this being passed in, etc etc.

[edit]
Observation: If I interrupt after calling flag()/unflag() by breaking debugger or hardcoding an exit, the flagging also "sticks" as expected. Is this something likely local to my environment?
[/edit]

Is there something about the flagged entity having just been updated also being the same one being flagged?

✨ Feature request
Status

Closed: outdated

Component

Flag core

Created by

πŸ‡ΊπŸ‡ΈUnited States texas-bronius

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024