0

When I enable, submit, and edit results in the webform example composite module, an extra item is automatically generated.

enter image description here

I'd like to keep "Add 1 more items", but remove the automatically generated "empty" composite item. I've done this with fields with this code:

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Hide Last Item in tag widget.
  $field_names = [
    'field_tags',
    'field_tags_two',
  ];
  foreach ($field_names as $field_name) {
    if (isset($form[$field_name])) {
      $max_delta = $form[$field_name]['widget']['#max_delta'];
      if (!$form_state->getBuildInfo()['callback_object']->getEntity()
          ->isNew() && isset($form[$field_name]['widget'][1])) {
        unset($form[$field_name]['widget'][$max_delta]);
        $form[$field_name]['widget']['#max_delta'] = $max_delta - 1;
      }
    }
    // Unset the Add another item button.
    unset($form[$field_name]['widget']['add_more']);
  }
}

How do I do this with webform composite elements?

1 Answer 1

0

The empty_items property needs to be set to 0. There may be a configuration for this, but I couldn't find it. Here's the code:

/**
 * Implements hook_webform_submission_form_alter().
 */
function my_module_webform_submission_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  /** @var \Drupal\webform\WebformSubmissionForm $form_object */
  $form_object = $form_state->getFormObject();

  /** @var \Drupal\webform\WebformSubmissionInterface $webform_submission */
  $webform_submission = $form_object->getEntity();

  $webform = $webform_submission->getWebform();
  $data = $webform_submission->getData();
  foreach ($data as $element_key => $element_value) {
    $element = $webform->getElement($element_key);
    if (!empty($element['#webform_key'])) {
      if ($element['#webform_key'] == 'my_composite') {
        $form['elements']['container']['my_composite']['#empty_items'] = 0;
      }
    }
  }
}

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.