2

I am implementing a custom form with file uploads and having trouble getting the form to post the files.

Here is my form code for the input:

for ($x = 1; $x <= $photo_count; $x++) {
    $form['photo_'.$x] = array(
      '#type' => 'file',
      '#name' => 'files[' . implode('_', $form['photo_'.$x]['#parents']) . ']',
      '#title' => t('Choose a file'),
      '#title_display' => 'invisible',
      '#theme_wrappers' => array(),
    );
  }

$photo_count is a variable set in the config settings for this module, so they can change the amount of photos a person can upload whenever.

In my validate:

foreach ($form_state['values'] as $key => $value) {
    if (preg_match('/photo_/', $key)) {
      $file_key = file_save_upload($key, array(
        'file_validate_is_image' => array(), // Validates file is really an image. 
        'file_validate_extensions' => array('png gif jpg jpeg'), // Validate extensions.
      ));
      // If the file passed validation:
      if ($file_key) {
        // Move the file, into the Drupal file system
        if ($file_key = file_move($file_key, 'public://temp_uploads')) {
         // Save the file for use in the submit handler.
         $form_state['values'][$file_key] = $file_key;
        } else {
         form_set_error($file_key, t('Failed to write the uploaded file the site\'s file folder.'));
        }
      }
    }
  }

Except when I dump $form_state on the validate/submit steps, it's always empty, and file_save_upload returns NULL.

I looked at a few examples on how to do this, and I think I have everything I need, but something is wrong. The form ENCTYPE is set to multipart, too. My form is multistep, implemented with CTools Wizard if that matters.

Edit:

If I dump $_POST and $form_state, there are no values for files. However, if I dump $_FILES, the files I chose are in the array and I can operate on them. Why are they not making their way into the POST or $form_state in Drupal?

2
  • That's odd. If $form_state is empty, file_save_upload should not return anything because according to your code it is never executed.
    – Oswald
    Aug 10, 2011 at 17:06
  • I know, I am confused. It may be something with CTools form wizard, but it is definitely in the $_FILES array. I am using that for now until I figure out why it's not getting into $form_state. I should also note its nowhere in $form_state, not just $form_state['values'].
    – Kevin
    Aug 10, 2011 at 18:15

1 Answer 1

1

I could not find a way to capture uploads into the Drupal Form API without looking at $_FILES and taking them that way. I still do not see files in $form_state values.

1
  • i've some issue. how to do this?
    – dobeerman
    Jun 2, 2012 at 12:34

Your Answer

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

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