2

I have a form with the following input field:

<input type="file" name="photo_files[]" />

I would like to save each of this files using file_save_upload and then change their status to permanent via file_save. It seems file_save_upload only takes a name and NOT an array. How can I accomplish this?

  • Just to make it clear that the form should be generated by Drupal or your form will not be validated. If it's a Drupal form that you have shown the HTML output, show us the form array as well. – AyeshK Oct 10 '12 at 23:00
1

Here is how you could do it.

function mymodule_testes($form, $form_state) {
// your form definition goes here
  $form = array();
  $form['upload'] = array( // note the key
    '#type' => 'file',
    '#title' => t('Choose a file'),
    '#weight' => -10,
  );

  $form['upload2'] = array(
    '#type' => 'file',
    '#title' => t('Choose a file'),
    '#weight' => -10,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('submit'),
  );

  return $form;
}

function mymodule_testes_validate($form, $form_state) {
  dpm($form_state);
  // pass proper args to file_save_upload .. see documentation 
  $file1 = file_save_upload('upload' , array()); // remember the key
  $file2 = file_save_upload('upload2' , array());
  // you dont have to do it verbosly
  // Do all your  validations  if(!$file1 || !$file2) form_set_error ...

  // save it onto form_State
  $form_state['files_storage'][0] = $file1 
  $form_state['files_storage'][1] = $file1
  dpm($file1);
  dpm($file2);

}


function mymodule_testes_submit($form, $form_state) {
 // using devel so you could see how it is stored 
 dpm($form_state);

  foreach ($form_state['files_storage'] as $key => $file) {
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
  }
}

Hope this helps

| improve this answer | |
0

Just loop through them in your submit handler:

foreach($form as $key => $item) {
  if($item['#type'] == 'file') {
    file_save_upload($key, array());
  }
}

That'll run file_save_upload on all form items with the type of 'file', you could also turn that conditional to an in_array() and select other file field types you could use.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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