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.