7
$form['picture']['file'] = array(
  '#type' => 'managed_file',
  '#title' => t('picture'),
  '#description' => t('Allowed extensions: gif png jpg jpeg'),
  '#default_value' => (isset($foo->picture->fid) ? $foo->picture->fid : ''),
  '#upload_location' => variable_get('picture_upload_location'),
  '#upload_validators' => array(
    'file_validate_extensions' => array('gif png jpg jpeg'),
    // Pass the maximum file size in bytes
    'file_validate_size' => array(MAX_FILE_SIZE*1024*1024),
  ),
);

I have the above code snippet from here. It's very useful, however I'm having a hard time setting #default_value.

What is $foo? Where is it set and how can I change it? Will I use the image uploaded on the other pages (coded in the same module).

2 Answers 2

6

Welcome to Drupal Answers. You just need to pass the fid integer value to the default value. To better understand what is fid see below description.

fid is Unique File id that is stored in the database for each and every uploaded file using Drupal File System.

So, if you want to set default image then it should be uploaded via Drupal File System. Ideally, you need to store fid of the uploaded file in a variable using variable_set in submit handler and do variable_get in default value to set fid. That's it !!

Hope it answers :-)

2
  • the problem is my image can be changed from time to time by user upload. that means i will be having different fid. i need to get the current fid so i will be able to set it as default_value Oct 19, 2012 at 6:47
  • Yes, for that you need to use variable_set in submit handler of the form where you set the fid of the uploaded file to a variable. And will be loading the same using variable_get ! Please read my updated answer :-)
    – Anil Sagar
    Oct 19, 2012 at 6:55
0

User can use the $_GET property if you are rendering file again without calling a submit function. If file is calling after submit function use the $form_state['values']['file']


$form['file'] = array(
    '#type' => 'managed_file',
    '#upload_location' => 'private://',
    '#weight' => 5,
    '#upload_validators' => array(
      'file_validate_extensions' => array('gif png jpg jpeg doc docx pdf xls xlsx rtf odt tiff'),
    ),
  );

  if (isset($_GET['file'])) {
      $form['file']['#default_value'] = $_GET['file'];
  }

Your Answer

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

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