Adding a delete button for webform attachment fields I have created a structure of field like below within code and not used webform UI. The reason of doing this pro-grammatically is because I have hundreds of forms and I wanted to do it once for all.



Here is my code:

            for ($i = 0; $i &lt;= 4; $i++) {
                $form['submitted']['file' . $i] = array(
                    '#title' =&gt; t('File'),
                    '#type' =&gt; 'managed_file',
                    '#description' =&gt; t('Please upload a document or image.'),
                    '#default_value' =&gt; variable_get('file' . $i, ''),
                    '#weight' =&gt; 100,
                );

                $form['submitted']['remove_name'.$i] = array(
                   '#type' =&gt; 'submit',
                   '#value' =&gt; t('Remove'.$i),
                   //I NEED A WAY TO PASS $i AS ARGUMENT TO THE CALLBACK
                   '#submit' =&gt; array('form_remove_attachment'),
                   // Since we are removing a name, don't validate until later.
                   '#limit_validation_errors' =&gt; array(),
                );
            }


And here is the callback:

 function form_remove_attachment($i, &amp;$form_state) {
  //dsm($form_state['complete_form']);
  $clicked = explode(' ', $form_state['clicked_button']['#value']);
  //dsm($clicked, 'clicked');
  if ($clicked[1] == $i) {
     unset($form_state['complete_form']['submitted']['file' . $i]);
  }
  // Setting $form_state['rebuild'] = TRUE causes the form to be rebuilt again.
  $form_state['rebuild'] = TRUE;
}


Now what I need is a delete button for each attachment field to allow users to change their mind on regard the attached files. I can add it of course by JS but this way the attachments are not eliminated from $form_state.

Does anyone have some suggestions?
There is an example in the examples module.

There is a module with in that called form_example. If you check the 9th example you would get what you are looking. It has an example of adding and removing fields dynamically and the code is well documented. 

change value '#value' =&gt; t('Remove'), to '#value' =&gt; t('Remove' . $i),

and in function you could get that as given below

function form_remove_attachment($i) {
    $clicked = explode(' ', $form_state['clicked_button']['#value']);
   //$clicked[1] would have the value of $i

    $form_state['rebuild'] = TRUE;
}