Add elements to webform dynamically via hook_form_alter I'm trying to dynamically add multiple toggle fields to a form (in my case webform) via a form-alter-hook.

function module_form_alter(&amp;$form, FormStateInterface $form_state, $form_id) {
....
  foreach ($roles as $role) {
    $form['elements'][$role-&gt;id()] = array(
      '#type' =&gt; 'webform_toggle',
      '#title' =&gt; t($role-&gt;label()),
      '#default_value' =&gt; 0,
      // More webform specific arguments follow here.
      '#webform_id' =&gt; "edit_membership_roles--" . $role-&gt;id(),
      '#webform_key' =&gt; $role-&gt;id(),
      '#webform_parent_key' =&gt; "",
      '#webform_parent_flexbox' =&gt; FALSE,
      '#webform_depth' =&gt; 0,
      '#webform_children' =&gt; [],
      '#webform_parents' =&gt; [$role-&gt;id()],
      '#webform_multiple' =&gt; FALSE,
      '#webform_composite' =&gt; FALSE,
      '#admin_title' =&gt; $role-&gt;id(),
      '#webform' =&gt; "edit_membership_roles",
      '#webform_submission' =&gt; NULL,
      '#access' =&gt; TRUE,
      '#webform_element' =&gt; TRUE,
      '#element_validate' =&gt; [],
    );
  }
}


This works in a way that the form is displayed correctly, with all dynamically added toggle elements. However, when trying to load the WebformSubmissionInterface $webform_submission via $webform_submission-&gt;getData(); in my custom class FormHandler extends WebformHandlerBase {...}, the array only contains the elements that I manually added to the webform via the GUI.

I checked the first answer of this question, but my $form does not have a $form['submitted']

Am I just missing something or does this approach not work at all?

Update

I did the same approach with a custom form built with Drupal FormApi and it works. So I must be missing something specific to webforms.
Adding elements dynamically via hook form alter does not work because the Webform module can't recognize the new elements.  Your best bet is to create a custom webform element.