0

I am trying to add products to cart with custom options. All are working but if custom options is file, it's not working. I've tried everything so far, but no luck. Anyone tried this and have a solution? TIA!

0

Apparently, I figured it out, Pls comment if I'm doing wrong,

For M2 (Magento2.4.2), the following worked for me: Suppose your form file upload html looks like below : (Loaded with core function)

<div class="control" id="input-box-options_22_file">
        <input type="file" name="options_22_file" id="options_22_file" class="product-custom-option required" aria-required="true">
        <input type="hidden" name="options_22_file_action" value="save_new" aria-required="true">
</div>

Then on your form submit you need an ajax request as well since Magento send binary of the file with params, but if you send it without ajax, probably only file name will be passed. To do ajax:

$('#addCart').on('submit',(function(e) {
    e.preventDefault();
    $.ajax({
         url: config.addCartUrl,
    type: "POST",
    data:  new FormData(this),
    contentType: false,
         cache: false,
    processData:false,
    });
        
    }));

In your addToCart.php you can traverse the options and if found with file you can do following:

foreach ($product->getOptions() as $o)
      {
       foreach ($o->getValues() as $value)
              {
                  //do traversing for other option types
               }   
       if($o->getType() == "file")
            {
              $params['options_'.$o->getOptionId().'_file_action'] = 
              $postParams['options_'.$o->getOptionId().'_file_action'];
            }
               //$postParams is params from form submitted
     }
       $this->cart->addProduct($product, $params);
//don't forget to append other required params for add to cart
  

This will add to cart products with custom option type "file" without issues hopefully.

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.