drupal-7drupal-fapi

Drupal 7, default_value for a file field in a custom form


I've created a formular where the user can upload an image using a file field. In another formular the user is able to change the image he previous uploaded.

So far I was able that the user can upload a new picture or let the field empty and the existing image remains. My question is, how do I show the user in a nice way which file he previously uploaded with the field? Setting a #default_value (@code below) does nothing for me.

//$smallimage = fid of image
$form['smallimage'] = array(
  '#type' => 'file',
  '#title' => t('Image'),
  '#default_value' => $smallimage,
  '#description' => t('Upload a file, allowed extensions: jpg, jpeg, png, gif'),
);

Edit: Switched back to managed files. I've no types to bind my files/images to so I bind them to the first node and the first user. Not a clean solution but it works.

Has anyone a solution/workaround without switching to managed_file?

Thank you in advance


Solution

  • On Drupal FAPI, '#default_value' is not a valid property for type "file", if you want to use the property #default_value in that case you can use

    '#type'         => 'managed_file'
    

    and your code should look like this,

    $form['file'] = array( 
        '#title'        => t('Upload image'),
        '#type'         => 'managed_file',
        '#description'  => t('Images must be one of jpg, bmp, gif or png formats.'),
        '#default_value' => $fid,  //here you need to provide the file id (get it from database or $file_obj->fid).
        '#upload_location' => 'public://'
    );