Score:0

Replace Tokens from Webform Submission in DOCX

ua flag

This is my first question here at Drupal Answers and I try to be as precise as possible.

I'm using Drupal 9 and the current version of the webform module. What I am trying to do is replacing tokens (placeholders) in a DOCX file with values submitted with a webform.

To get this work I wrote a custom Webform Handler. This handler provides a file upload where I submit the DOCX that contains the placeholders, which should be replaced later. The file upload works, the handler is able to load the file during submission:

public function submitForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
...
}

However, I am not able to replace the tokens from the webform/submission in the DOCX using this code:

$token_service = \Drupal::token();
$token_options = ['clear' => TRUE];
$data = array(
    'webform' => $webform,
    'webform-submission' => $webform_submission,
);
$xml = $token_service->replace($xml, $data, $token_options);

$xml is the complete text from the DOCX. $webform is the webform object loaded from the submission $webform = $webform_submission->getWebform();

The string I got from the DOCX (extracting the zip and load the XML) contains "tokens" exactly as the tokens that are the fields in my webform. Example: [submission:values:angaben_zur_zukuenftigen_gesellschaft:gesellschaftssitz]

The webform contains a fieldset with the machine name angaben_zur_zukuenftigen_gesellschaft as well as a field with the machine name gesellschaftssitz. Respecting this the formatting in the DOCX file should be correct. Nevertheless I'm not able to replace the tokens in the DOCX with tokens from the webform submission even when $token_service->replace($xml, $data, $token_options); returns a string with cleaned tokens. That means the token replace method itself works but not with the provided data - they can't be used to replace the DOCX tokens.

I appreciate any help.

Alex

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.