0

Using Webform 6.2.0-beta5 on D10.0.9.

I have created a custom webform with a module; this is working perfectly.

Now I need to make several changes to the webform; some values will be calculated within my custom module, used as the default value for fields, and then the fields will be hidden.

With this code I can see the $webform details:

function mymodule_webform_submission_prepare_form(WebformSubmissionInterface $webform_submission, $operation, FormStateInterface $form_state) {
  $webform = $webform_submission->getWebform();
  if ($webform->id() == 'custom_webform_id') {
    \Drupal::messenger()->addStatus($webform);
  }
}

How do I now, for example:

  1. Add a value to a webform field
  2. Hide that webform field from the user

This will have the effect of programmatically adding values to the webform fields.

Thanks

4
  • 1
    Different hooks operate at different stages, so the "best" hook depends on the specific thing you are trying to do. Please update the question with the actual code you have written so far for what you are trying to accomplish. hook_form_alter() and hook_form_FORM_ID_alter() are the same except that hook_form_alter() runs for all forms and hook_form_FORM_ID_alter() runs only for the specified FORM_ID. May 14, 2023 at 1:26
  • I've not written any code yet. I want to change the form before it is rendered to the user.
    – Glenn
    May 14, 2023 at 1:49
  • Is the goal here to "calculate some values in custom code and then submit those values with the webform as a hidden field"? May 14, 2023 at 3:31
  • @PatrickKenny Yes, that's exactly what I need to do
    – Glenn
    May 14, 2023 at 4:01

1 Answer 1

0

Goal: Add some hidden fields to a webform, calculate the values for those fields in custom code, and then submit them with the webform.

You could use a hook for this, but I think there's a better approach: standard Webform hidden fields with a custom token.

Webfoorm supports creating hidden fields in the UI, so just create the fields you need there.

Then, you can set the value of the hidden fields to a token-- this is where your custom code comes in. You can create tokens in a custom module, and then, after you rebuild the cache, your tokens will be available for use in webform.

Here's a tutorial about creating tokens, and the Examples module also has sample code for creating tokens.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.