Score:0

How do I programmatically attach a file to a webform submission

ua flag

I'd like to attach a custom file to an email of a webform submission. That means, I want to add the file as email attachment without an existing webform field (document file) or similar.

My idea was to create a custom field programmatically in the method

public function preSave(WebformSubmissionInterface $webform_submission) {...}

that will be used as attachment. However, this doesn't work at all.

The file to be attached is a dynamically created file (as part of my own logic in the preSave method) that is stored in the "sites/default/files/..." folder and not managed.

How can I achieve this task?

unusedspoon avatar
aq flag
A better approach might be to use a hook to alter the mail webform sends and attach the file there. Unless you specifically need it to show as part of the submission within Drupal?
cn flag
If the file name has a predictable name, you don't need to associate it with a field; you can just attach the file by its name in your code. If you want to give the file an unpredictable name, you could use a hidden text field and set the value to the file name when it is generated.
Alex avatar
ua flag
Thank you both for your replies! I already had the idea to attach the file in hook_mail_alter. How can I access the submission data in the hook_mail_alter function? In Drupal 7 there was the $message['params']['submission'] element but not in Drupal 9. I need the submission data to process some logic before attaching the file.
unusedspoon avatar
aq flag
I've not done it but the submissions are content entities so if the submission ID is there then you'd just need to do an entity load for that entity type. Something like https://drupal.stackexchange.com/questions/262842/load-webform-submission
Alex avatar
ua flag
Thank you for the ideas. I was able to get it working: `$message['params']['webform_submission']` That is the submission object (\Drupal\webform\Entity\WebformSubmission) that I can use to load the configuration from my custom webform handler, process the file I'd like to attach and of course attach the file finally.
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.