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
$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
-
-
-
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']);
– LeksatCommented Oct 15, 2016 at 6:39 -
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.– GarrettCommented Jun 18, 2011 at 14:39
-
4I believe you can use #upload_validators: $form['file']['#upload_validators']['file_validate_extensions'][0] = 'png jpg gif pdf'; 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.– GarrettCommented 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– BartCommented Jun 22, 2011 at 9:15