How to set a custom option of type “file” when adding a product to the cart in Magento?

匿名 (未验证) 提交于 2019-12-03 07:36:14

问题:

Using my own controller, I'm adding a product to the Magento cart. It has 3 custom options: 2 dropdown options (color and size) and a file option (design). The code adding the product to the cart is

// obtain the shopping cart $cart = Mage::getSingleton('checkout/cart');  // load the product $product = Mage::getModel('catalog/product')     ->load($productId);  // do some magic to obtain the select ids for color and size ($selectedSize and $selectedColor) // ...  // define the buy request params $params = array(     'product'       => $productId,     'qty'           => $quantity,     'options'       => array(         $customOptionSize->getId()  => $selectedSize,         $customOptionColor->getId() => $selectedColor,          // set the file option, but how?      ), );  // add this configuration to cart $cart->addProduct($product, $paramObject); $cart->save();  // set the cart as updated Mage::getSingleton('checkout/session')->setCartWasUpdated(true); 

My question is: How do I attach a certain file to the design option?

The file has already been transferred to the server side (actually via the request). I could, however, fake uploading if this would be required. But until now I have not found a single source of information on setting file custom options...

My best guess from a tour through the Magento sources, is that the buy request needs some additional data (not in the options, but in the params object), like: option_123_file => something, but what exactly is needed I did not figure out yet. This part of the Magento sources is rather, uhh, not so straight forward. Thanks for any help.

回答1:

Ok finally figured this out. The params array needs special entry to tell the custom option with the key "options_xx_file_action" what to do with a file ('save_new' or 'save_old'). This would look like:

$params = array(     'product'       => $productId,     'qty'           => $quantity,     'options'       => array(         $customOptionSize->getId()  => $selectedSize,         $customOptionColor->getId() => $selectedColor,     ),     'options_'.$customOptionDesign->getId().'_file_action'=>'save_new', ); 

Obviously, you will need to add the file to the post request (via form or therelike). The name of the file should be "options_xx_file". For example, in my case my $_FILES looked like:

Array ( [options_108_file] => Array     (         [name] => i-like.png         [type] => application/octet-stream         [tmp_name] => C:\xampp\tmp\phpAAB8.tmp         [error] => 0         [size] => 6369     )  ) 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!