简体   繁体   English

添加到购物车中带有magento虚拟产品的自定义选项

[英]add to cart with custom option for virtual product in magento

I have a one controller class that can work for adding item to cart. 我有一个控制器类,可以用于将商品添加到购物车。 My scenario is 我的情况是
My Product has two custom options . 我的产品有两个自定义选项 One is Child and another one is infant. 一个是儿童,另一个是婴儿。
I want to add one custom options from these two into my shopping cart. 我想将这两个中的一个自定义选项添加到我的购物车中。 But, I try it many different way. 但是,我尝试了许多不同的方法。 But, I can't see any custom option in checkout page. 但是,我在结帐页面上看不到任何自定义选项。 How can I do that. 我怎样才能做到这一点。 Here my code sample. 这是我的代码示例。

public function indexAction() {
    $products = explode(',', $this->getRequest()->getParam('products'));
    $cart = Mage::getModel('checkout/cart'); 
    $cart->init(); 
    foreach ($products as $product_id) { 
    if ($product_id == '') { 
continue; 
    } 
    $pModel = Mage::getModel('catalog/product')->load($product_id); 
    $param = array(
        'qty' => 2,
        'options' => array(
        'option_id' => $product_id,
        'default_title' => "Ticket for Child or Infant",
        'title' => "Child 2 to 12"
        )
    );  
    if ($pModel->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_VIRTUAL) { 
       $cart->addProduct($pModel, new Varien_Object($param));
       Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
    }
    $cart->save();
    $this->_redirect('checkout/cart'); 
}  

Soooo, you have to very manually add an item to a shopping cart. 如此,您必须非常手动地将商品添加到购物车中。 This is how... 这就是...

$cart = Mage::getSingleton("checkout/cart");

// $products_to_add is something I made up... 
// associative array of product_ids to an array of their custom options
foreach ($products_to_add as $product_id => $custom_options) {
  $product = Mage::getModel("catalog/product")->load($product_id);
  $options = new Varien_Object(array("options" => $custom_options,
                                     "qty" => 1));

  // some products may result in multiple products getting added to cart
  // I believe this pulls them all and sets the custom options accordingly
  $add_all = $product->getTypeInstance(true)
      ->prepareForCartAdvanced($options, $product, Mage_Catalog_Model_Product_Type_Abstract::PROCESS_MODE_FULL);

  foreach ($add_all as $add_me) {
    $item = Mage::getModel('sales/quote_item');
    $item->setStoreId(Mage::app()->getStore()->getId());
    $item->setOptions($add_me->getCustomOptions())
      ->setProduct($add_me);

    $item->setQty(1);
    $cart->getQuote()->addItem($item);
  }
}

// when done adding all the items, finally call save on the cart
$cart->save();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM