I have a custom form in D8. Form has managed_file field. I am facing challenge regarding the limit of number of files upload to this field.

I have to make this managed_file field to upload only 3 images.

Can someone help me regarding this?


I can highly recommend DropzoneJS. It is a well maintained project, and will make it not only very easy for you to add a file upload widget with a specified max of files (or unlimited), it also provides a superior UX.

You can grab the module here: https://www.drupal.org/project/dropzonejs

Once you clone down the library from their GitHub repo, and enable the module, adding the form element is fairly straightforward:

$form['files_to_upload'] = [
  '#type' => 'dropzonejs',
  '#title' => 'Add some files!',
  '#description' => 'Add your files here!',
  '#dropzone_description' => 'Drop the files in here, please!',
  '#max_filesize' => '50M',
  '#extensions' => 'png jpg zip',
  '#max_files' => '3',

Which lets you upload 3 files and no more, in this example: example upload form

When you submit, you'll have the temp files available to loop through and add to managed, or do as desired with the data:

xdebug showing submitted values

There's a lot of neat functionalities that I'm not covering here. But, I've never regretted implementing this module, and it should hopefully help you out in your use case!

  • But I can't use dropzonejs module. I have to implement this using managed_file field type. – Pankaj Sachdeva Jun 7 at 6:20

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.