Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a proper Drupal 7 form api managed_file tutorial?

I've searched over the internet for half an hour but cannot find one.

I want to use the managed_file form api in D7 to allow use upload image file; more specifically, I think "#upload_validators" property may do the trick (if possible, to validate file extension before uploading; or at least, validate in the validation phase but not in the submit function). I've checked the image_example and file_example in the example modules, but cannot find a proper usage of it.

So I wonder if there's a proper tutorial on managed_file? Thanks a lot.

Update: I saw an example after doing a search on drupal directory from file.field.inc, and following the example, wrote code like this:

$form['file_upload'] = array(
  '#type'   => "managed_file",
  '#title'  => t("Upload"),
  '#descripion' => t("Only Image Files are allowed."),
  '#progress_indicator' => "bar",
  '#upload_location'    => "public://img/dish",
  "#upload_validators"  => array("file_validate_extensions" => "png gif jpg"),
);

This solved the problem.

like image 672
songyy Avatar asked Jul 17 '12 02:07

songyy


1 Answers

Here's an example of the managed_file field in use which includes #upload_validators as taken from https://drupal.stackexchange.com/a/5630/1103

$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),
  ),
);
like image 69
nmc Avatar answered Sep 28 '22 05:09

nmc