0

I successfully managed to save a flag programmatically in Drupal 8 thanks to this help but I cannot manage to save data into a custom field I added to the flag entity.

The following code saves the flag but the field stay empty.

$entity = \Drupal::entityTypeManager()->getStorage('node')->load($entity_id);
$flag_id = 'bookmark';
$flag_service = \Drupal::service('flag');
$flag = $flag_service->getFlagById($flag_id);

/* Here is where I'm trying to set my custom field value */
$flag->set('field_my_custom_field', $link_name);

$flag_service->flag($flag, $entity);

I cannot find any info into the documentation. Any help will be much appreciated.

  • Welcome to Drupal Answers! 👏 Have you tried $flag->save(); after the set? – leymannx May 7 at 7:18
  • Hi @leymannx, thanks :). Yes, that was my first try but no luck with it. – Davide Catani May 7 at 8:26
2

I fix it with this code. You should save the output of the function

$flag_service->flag($flag, $entity);   //Wrong method

in a variable like it

$id_flagged_entity = $flag_service->getFlagging($flag, $entity);

and set the title at this entity

$id_flagged_entity->set("field_my_custom_field", $link_name);
$id_flagged_entity->save();
| improve this answer | |
  • That's it! It works like a charm, thank you! – Davide Catani May 7 at 10:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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