Score:0

Auto assign term to node from term field from user

in flag

I have a term field called "Organization" on both Content and User entities.

On the Content entity, the field for Organization is hidden.

For the user, they select a value for Organization.

I'd like to automatically assign a value on a Node to be equal to the value of Organization in the User entity (if available, other leave empty).

There seems to be a number of ways to do this:

  • Rules, ECA, and other workflow tools
  • Context ecosystem of modules
  • Prepopulate modules

Constraints include: speed: cannot have node saving slow down due to workflow.

I'm hoping someone has experience implementing such a feature and would kindly shed some light to their approach.

Score:2
cn flag

Can easily create a custom module with the following

use hook_entity_presave ...

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_entity_presave/9.4.x

your code would look something like this...

 use Drupal\node\NodeInterface;

 function YOURMODULE_node_presave(NodeInterface $node) {
   switch ($node->getType()) {
     case "your_content_type":
       
       // Get the current user or //$node->getOwnerId();
       $user = \Drupal::entityTypeManager()->getStorage('user')->load(\Drupal::currentUser()->id());
       // Probably check if is set ect.. 
       $user_org = $user->field_organization->target_id; 
       $node->set('field_organization', $user_org);
     break;
   }
  }

This should not slow saving down too much at all - as making con jobs or adding stuff to the a queue worker to do later would be silly in this case as needing it on a node.

I sit in a Tesla and translated this thread with Ai:

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.