Drupal 7 retain file upload
Asked Answered
N

2

1

I have a file upload form

how can I retain this file when there are other validation errors so that the user doesn't have to upload the file again?

I tried this in my validation function but it doesn't work:

function mymodule_someform_validate($form, &$form_state) {
  $form_state["values"]["some_field"] = some_value;
}

the $form_state["values"] variable is not available in my form definition function - mymodule_someform($form, &$form_state)

Any ideas?

Niggardly answered 12/10, 2011 at 11:27 Comment(0)
C
1

Just use the managed_file type, it'll do it for you:

$form['my_file_field'] = array(
  '#type' => 'managed_file',
  '#title' => 'File',
  '#upload_location' => 'public://my-folder/'
);

And then in your submit handler:

// Load the file via file.fid.
$file = file_load($form_state['values']['my_file_field']);

// Change status to permanent.
$file->status = FILE_STATUS_PERMANENT;

// Save.
file_save($file);

If the validation fails and the user leaves the form, the file will be automatically deleted a few hours later (as all files in the file_managed table without FILE_STATUS_PERMANENT are). If the validation doesn't fail, the submit handler will be run and the file will be marked as permanent in the system.

Creed answered 12/10, 2011 at 11:34 Comment(1)
yeah, I'll probably just use the default node form. I wanted to do a custom form because I didn't want to user the node's form with it's ajax file upload. but I still don't know why the form_state passed to the form definition function doens't have the "values" set up...Niggardly
D
0

Admin form example for others who may be looking:

function example_admin_form(){  

  $form = array();  

  $form['image'] = array(
      '#type' => 'managed_file',
      '#name' => 'image',
      '#title' => t('upload your image here!'),
      '#default_value' => variable_get('image', ''),
      '#description' => t("Here you can upload an image"),
      '#progress_indicator' => 'bar',
      '#upload_location' => 'public://my_images/'
  );

  // Add your submit function to the #submit array
  $form['#submit'][] = 'example_admin_form_submit';

  return system_settings_form($form);
}

function example_admin_form_submit($form, &$form_state){

  // Load the file
  $file = file_load($form_state['values']['image']);

  // Change status to permanent.
  $file->status = FILE_STATUS_PERMANENT;

  // Save.
  file_save($file);

}
Desulphurize answered 19/10, 2013 at 15:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.