Skip to content

Instantly share code, notes, and snippets.

@phannam1412
Created November 2, 2016 06:27
Show Gist options
  • Save phannam1412/d09675bf89f755e8c9dad1aca6209381 to your computer and use it in GitHub Desktop.
Save phannam1412/d09675bf89f755e8c9dad1aca6209381 to your computer and use it in GitHub Desktop.
Magento helper functions
<?php
class MagentoHelper {
function addSimpleProductToWishlist($productId, $customerId) {
$wishlist = Mage::getModel('wishlist/wishlist')->loadByCustomer($customerId, true);
$product = Mage::getModel('catalog/product')->load($productId);
$buyRequest = new Varien_Object(array()); // any possible options that are configurable and you want to save with the product
$result = $wishlist->addNewItem($product, $buyRequest);
$wishlist->save();
}
// $parentId = <grouped_product_id > Id of the grouped product
// $children = array('<child_id_1>', '<child_id_2>', '<child_id_3>'); Create an array of associated products
// $child_qty Quantity of each child product to be addede to cart
function addGroupedProductToCart($parentId, $children,$child_qty) {
//Array for holding the associated products
$super_group = array();
//Add all child products to $super_group with product_id as key and quantity as value
foreach($children as $child) {
if(intval($child)) {
$super_group[ $child ] = $child_qty;
}
}
//Add Grouped product to cart
try {
//Get object of main grouped product
$product = Mage::getModel('catalog/product')->load($parentId);
//Check product availability
if( ! $product) {
echo "Error in product!";
return;
}
//Get cart object
$cart = Mage::getModel('checkout/cart');
//Create params for grouped product
$params = array('super_group' => $super_group);
//Add product to cart with specified parameters and save the cart object
$cart->addProduct($product, $params)->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
echo $this->__('%s was added to your shopping cart.', Mage::helper('core')->htmlEscape($product->getName()));
}
catch(Mage_Core_Exception $e) {
if(Mage::getSingleton('checkout/session')->getUseNotice(true)) {
echo $this->__($e->getMessage());
}
else {
$messages = array_unique(explode("n", $e->getMessage()));
foreach($messages as $message) {
echo "<br />".$message;
}
}
}
catch(Exception $e) {
echo $this->__('Cannot add the item to shopping cart.');
}
}
function addSimpleProductToCart($productId,$quantity) {
// @todo should implement
}
function addGroupedProductToWishlist($productId) {
// @todo should implement
}
function getAddToCartUrlForGroupedProduct($grouped_product,$simple_product_id) {
return $this->helper('checkout/cart')->getAddUrl($grouped_product, []) . 'qty/1?super_group['.$simple_product_id.']=1';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment