2012-12-04 220 views
4

我必須創建一個(虛擬,簡單)產品,然後以編程方式添加到購物車,至此我已完成此操作。現在,我必須在此產品添加到購物車時設置自定義選項。但沒有任何反應。這裏是我的代碼使用自定義選項將產品添加到購物車

$product = Mage::getModel('catalog/product')->load($product_id); 

    $cart = Mage::getModel('checkout/cart'); 
    $cart->init(); 


    $params = array(
     'product' => $product->getId(), // This would be $product->getId() 
     'qty' => 1, 
     'options' => array(
      34 => "value", 
      35 => "other value", 
      53 => "some other value" 
     ) 
    );  



    try { 
     $cart->addProduct($product, new Varien_Object($params)); 
     Mage::getSingleton('checkout/session')->setCartWasUpdated(true); 
     $cart->save(); 
    } 
    catch (Exception $ex) { 
     echo $ex->getMessage(); 
    } 
+0

如果您用'$ params'替換'新的Varien_Object($ params)',它會起作用嗎? – Ossie7

+0

那麼這個作品,我現在就想它。它在qoute_item表中添加了這個值。但價值對購物車頁面不可見。就像我們從後端添加的其他自定義選項一樣。 –

回答

6

這是代碼我想出了成功。

$a_options = array(
    'options' => array(
     'label' => 'Choice', 
     'value' => $pkg_selected_products, 
    ) 
); 

$quoteItem->addOption(new Varien_Object(
    array(
     'product' => $quoteItem->getProduct(), 
     'code' => 'additional_options', 
     'value' => serialize($a_options) 
    ) 
)); 

$quote->addItem($quoteItem); 
$quote->save(); 
+0

添加後我得到空白頁面 –

+0

它爲可配置產品給出錯誤 –

+0

它會在購物車頁面中添加文本。我們如何使用這個圖像(即選項類型是圖像) –

0

我遇到了日期自定義選項字段的問題,用於通過我的控制器功能添加產品。

所以我必須打破/ Magento的方式爆炸,並把它的參數AddProduct(),如下所示。

try { 
     $cart = Mage::getModel('checkout/cart'); 
     $previousItemCount = $cart->getQuote()->getItemsCount(); 

     if ($previousItemCount <= 0) { 
      $cart->init(); 
     } 

     $params = $this->getRequest()->getParams(); 
     $product = Mage::getModel('catalog/product')->load($params['product_id']); 

     $date = explode('/', $params['product_dtinvoice']); 
     $date = array(
      'month' => $date[0], 
      'day' => $date[1], 
      'year' => $date[2], 
     ); 

     $cart->addProduct(
      $product, 
      new Varien_Object(array(
       'product' => $product->getId(), 
       'qty' => 1, 
       'options' => array(
        '4' => array(
         'month' => $date['month'], 
         'day' => $date['day'], 
         'year' => $date['year'] 
        ), 
        '2' => $params['product_ean'], 
        '3' => $params['product_serialnumber'], 
        '1' => $params['product_seller'], 
       ), 
      )) 
     ); 

     $cart->save(); 

     if ($previousItemCount < $cart->getQuote()->getItemsCount()) { 
      $return = array('result' => true, 'msg' => ''); 
     } else { 
      $return = array('result' => false, 'msg' => 'Did not possible to add this product to cart. Please contact the administrator'); 
     } 

     $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($return)); 
    } catch(Exception $e) { 
     Mage::throwException($e->getMessage()); 
    } 
相關問題