26

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.

40
$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),
  ),
);
  • 1
    I tried the file_validate_size, but it does not working. – ARUN Oct 8 '14 at 11:45
  • It doesn't work for me to. – Mr_DeLeTeD Nov 19 '14 at 10:06
  • wehre come from $foo? – khaled_webdev Jul 21 '15 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 Oct 15 '16 at 6:39
  • This works also in Drupal 8. – sanzante Feb 23 '17 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.

  • 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 Jun 18 '11 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 Jun 18 '11 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 Jun 20 '11 at 13:37
  • Note: there is no managed_file form field in Drupal 6, only file. Source: Drupal 6 Form API reference – Bart Jun 22 '11 at 9:15

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.