Score:1

Running a hook after node save, or another way to get the file name attached to a node

ls flag

We've a D9 site with a custom module which generates and saves CSS code. It takes the name of the file attached to a node, and generates CSS to set it as the node's background.

Initially, I tried getting the file name from $node in the _node_presave hook, but $node does not contain it. What it does contain is the nid. So we're using that with $nodeContent = \Drupal\node\Entity\Node::load($nid) to load the node, which then allows for $file = $nodeContent->get('field_cover_image')->entity;.

I've gone through the list of available hooks to run this code after node save, but have not found anything that does the job. Doing this task in node_presave means the node has to be re-saved, without altering the filename after the initial save (else the filename used initially ends up in our CSS, and our solution doesn't work.)

Digging deeper, I found that the only place in the DB where the file name is available is in the file_managed table, and only as part of longer data string that I don't fully understand.

What is an efficient way to get the name of the file attached to a node field on initial node save, so we can use it to generate CSS real time, on the first run?

A solution where we somehow trick the system into doing a second save in the background works as an alternative.

ru flag
Not really an answer to your question, but I had a similar task and created a [module that generates TailwindCSS on thy fly](https://www.drupal.org/project/tailwind_jit). Might be an alternative solution
cn flag
You might be able to use `hook_ENTITY_TYPE_insert()`, which runs after `hook_node_save()`: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_ENTITY_TYPE_insert/10
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.