JavaScript Upload field update config

If you need to dynamically update the config of the upload field based on some inputs on your page, you can use the JavaScript API of the widget to update the field config.

UpdateConfig API

UploadField.updateConfig(config: {}): void

Config Object:

{
	required: true, // upload required,
	fileMultiple: true, // allow multiple file uploads
	fileCountMin: 0,  // in case of multiple uploads min
        fileCountMax: 2  // in case of multiple uploads max
}

Example:

If you want to change the minimum upload count based on a variant selection on the product form you can use the following code:

var field;
var selector = 'select'; // update to match your theme's variant selector

function applyConfig(value) {
   if (!field) return;

   // check if specific value is selected
   var isSelected = value.indexOf('YES') !== -1;

   field.updateConfig({
      "fileCountMin": isSelected ? 2 : 1,
      "fileCountMax": isSelected ? 2 : 1
   });
}

// listener to get a reference to the upload field
window.addEventListener('upload:ready', function (e) {
   // store field reference
   field = e.detail;

   // apply the config for the value that is already selected on page load
   var el = document.querySelector(selector);
   if (el) applyConfig(el.value);
});

// watch changes to the variant selector
var variantSelect = document.querySelector(selector);
if (variantSelect) {
   variantSelect.addEventListener('change', function () {
      applyConfig(this.value);
   });
}
Did this answer your question? Thanks for the feedback There was a problem submitting your feedback. Please try again later.