30

Not having any luck find this in Drupal documentation or developer examples. I need to set a managed_file form field to only allow zip files in a Drupal 7 custom module.

2 Answers 2

49
$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),
  ),
);
5
  • 1
    I tried the file_validate_size, but it does not working.
    – Cool
    Commented Oct 8, 2014 at 11:45
  • It doesn't work for me to.
    – Mr_DeLeTeD
    Commented Nov 19, 2014 at 10:06
  • wehre come from $foo? Commented Jul 21, 2015 at 8:53
  • It seems like validation does not happen automatically if you save a file manually. I had to do it like this: $file = file_save_upload('file', $form['picture']['file']['#upload_validators']);
    – Leksat
    Commented Oct 15, 2016 at 6:39
  • This works also in Drupal 8.
    – sanzante
    Commented Feb 23, 2017 at 13:25
1

I am not sure if you are using Drupal 6 or Drupal 7, but in Drupal 6 you would choose:

  • Admin > Content > Content Types > [Your Content Type] > Manage Fields > [Edit your file field] and look for the field setting of "Permitted upload file extensions"

  • In that field, enter zip

Drupal 7 is probably similar. Look for Content Types under Admin > Structure.

4
  • Drupal 7, sorry for the omission. I'm using a managed_field form item in a custom module, so the admin isn't going to help. I need a programming solution.
    – Garrett
    Commented Jun 18, 2011 at 14:39
  • 4
    I believe you can use #upload_validators: $form['file']['#upload_validators']['file_validate_extensions'][0] = 'png jpg gif pdf';
    – NEAR DARK
    Commented Jun 18, 2011 at 17:16
  • NEAR DARK wins it. It took pasting in that line to realize that I had a typo in my original form item array. So basically, this is a well documented feature of the form api that I wasn't getting because of a spelling error. Sorry guys.
    – Garrett
    Commented Jun 20, 2011 at 13:37
  • Note: there is no managed_file form field in Drupal 6, only file. Source: Drupal 6 Form API reference
    – Bart
    Commented Jun 22, 2011 at 9:15

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.