Magento remove item from cart from observer - magento

Is there any way that we can remove the Items from the cart. Actually I have dynamic Grouped products were I need to allow the user to buy the item inside the grouped product. Now when someone only select the Item under the grouped product then it allow to buy that and need to stop or remove the group product from the cart.
I had tried with checkout_cart_product_add_after Observer and used below logic, but it is not working
$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
foreach ($items as $item) {
if ($item->getProduct()->getId() == $productId) {
$itemId = $item->getItemId();
$cartHelper->getCart()->removeItem($itemId)->save();
break;
}
}
return;
Please help me guys.
Thanks in advance.

Standalone example:
$oCheckout = Mage::getSingleton( 'checkout/session' );
$oQuote = $oCheckout->getQuote();
var_dump( $oQuote );
$oCart = $oQuote->getAllItems();
if( !empty( $oCart ) )
{
foreach ( $oCart as $oItem )
{
// Specify conditionals
if( $oItem->getProduct()->getSku() == 1 )
{
// Note to use Shopping cart id not product id.
$oQuote->removeItem( $oItem->getId() )
->save();
}
}
}
var_dump( $oQuote );

Try this in your observer:
$product = $observer->getEvent()->getProduct();
$cart = Mage::getSingleton('checkout/cart');
foreach ($cart->getQuote()->getItemsCollection() as $_item) {
if ($_item->getProductId() == $product->getId()) {
$_item->isDeleted(true);
}
}
}

Related

Magento: how to get the quantity of each bundle option that was ordered

//Observer function
$order = $observer->getEvent()->getOrder();
foreach($order->getAllItems() as $item){
if($item->getProductType() == 'bundle')
{
//Loading bundle product object
$bundle_product = Mage::getModel('catalog/product')->load($item->getProductId());
//Getting bundle items collection
$selectionCollection = $bundle_product->getTypeInstance(true)->getSelectionsCollection($bundle_product->getTypeInstance(true)->getOptionsIds($bundle_product), $bundle_product);
foreach($selectionCollection as $option)
{
//Loading each bundle item
$bundle_item = Mage::getModel('catalog/product')->load($option->getId());
//How to get the quantity that was ordered? example:
$bundle_item->getQtyOrdered(); //Note: I know this is wrong, this is not the correct object.
}
}
}
Please use below code:
//Observer function $order = $observer->getEvent()->getOrder();
foreach($order->getAllItems() as $item){
if($item->getProductType() == 'bundle')
{
$options = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct());
$bundleOption=$options['info_buyRequest']['bundle_option_qty'];
foreach($bundleOption as $bundleItemQty){
echo 'Bundle Item Qty='.$bundleItemQty;
}
}
}

How know if an attribute in Magento use options

I want to know programmatically if a magento attribute use options or not to know if I must displayed this options.
For example a Text attribute don't use it and a Dropdown attributes have option. But how make programmatically this distinction ?
$product = Mage::getModel('catalog/product')->load($product_id);if($product->hasOptions){
$optionsArr = $product->getOptions();
foreach($optionsArr as $optionKey => $optionVal)
{
$options=array();
foreach($optionVal->getValues() as $valuesKey => $valuesVal)
{
$options[]=array("key"=>$valuesVal->getId(), "val"=>$valuesVal->getTitle());
}
$custom_option["titles"][]=array("title"=>$optionVal->getTitle(),"title_id"=>$optionVal->getId(),"options"=>$options);
//$optStr.= "</select>";
}
$attributeCode = 'code_here';
$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', $attributeCode);
if ($attribute->getSourceModel()) {
//it has options
} else {
//it does not have options
}
$attributeModel = Mage::getModel ( 'eav/entity_attribute' )->loadByCode ( 'catalog_product', 'attribute_code' );
if ($attributeModel->getData ( 'frontend_input' ) == 'select') {
$attribute = Mage::getSingleton ( 'eav/config' )->getAttribute ( 'catalog_product', 'attribute_code' );
if ($attribute->usesSource ()) {
$options = $attribute->getSource ()->getAllOptions ( false );
$ifoptionfound = false;
if($options)
$ifoptionfound = true;
}
}

Magento products from attribute

I have the following code, which will get all products from all orders for one logged in customer which works fine. I want to add to this code so that it only returns products from a specified attribute set. I believe I have both bits of code that I need they just won't work together.
Code I want to add to is:
<?php
if (Mage::getSingleton('customer/session')->isLoggedIn()) {
/* Get the customer data */
$customer = Mage::getSingleton('customer/session')->getCustomer();
/* Get the customer's email address */
$customer_email = $customer->getEmail();
$customer_id = $customer->getId();
}
$collection = Mage::getModel('sales/order')->getCollection()->addAttributeToFilter('customer_email', array(
'like' => $customer_email
));
$uniuqProductSkus = array();
foreach ($collection as $order) {
$order_id = $order->getId();
$order = Mage::getModel("sales/order")->load($order_id);
$ordered_items = $order->getAllItems();
foreach ($ordered_items as $item)
{
if (in_array($item->getProduct()->getSku(), $uniuqProductSkus)) {
continue;
} else {
array_push($uniuqProductSkus, $item->getProduct()->getSku());
echo various variables here;
}
}
}
?>
Code I have used before to get products from a specified attribute set
$attrSetName = 'Beer';
$attributeSetId = Mage::getModel('eav/entity_attribute_set')
->load($attrSetName, 'attribute_set_name')
->getAttributeSetId();
//Load product model collecttion filtered by attribute set id
$products = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('name')
->addFieldToFilter('attribute_set_id', $attributeSetId);
You can add this piece of code to make your script work in the foreach loop.
$product = Mage::getModel('catalog/product')->load($sku, 'sku');
$attributeSetModel = Mage::getModel("eav/entity_attribute_set");
$attributeSetModel->load($product->getAttributeSetId());
$attributeSetName = $attributeSetModel->getAttributeSetName();
if(0 == strcmp($attributeSetName, 'Beer') {
//add your logic
}else{
continue;
}
Update:
<?php
if (Mage::getSingleton('customer/session')->isLoggedIn()) {
/* Get the customer data */
$customer = Mage::getSingleton('customer/session')->getCustomer();
/* Get the customer's email address */
$customer_email = $customer->getEmail();
$customer_id = $customer->getId();
}
$collection =
Mage::getModel('sales/order')->getCollection();
$collection->addAttributeToFilter('customer_email', array(
'like' => $customer_email
));
$uniuqProductSkus = array();
foreach ($collection as $order) {
$order_id = $order->getId();
$order = Mage::getModel("sales/order")->load($order_id);
$ordered_items = $order->getAllItems();
foreach ($ordered_items as $item)
{
$item->getProduct()->getSku();
if (in_array($item->getProduct()->getSku(), $uniuqProductSkus)) {
continue;
} else {
$attributeSetModel = Mage::getModel("eav/entity_attribute_set");
$attributeSetModel->load($item->getProduct()->getAttributeSetId());
$attributeSetName = $attributeSetModel->getAttributeSetName();
if(0 == strcmp($attributeSetName, 'Beer')) {
array_push($uniuqProductSkus, $item->getProduct()->getSku());
// echo various variables here;
}else{
continue;
}
}
}
}
print_r($uniuqProductSkus);
?>

Remove 1 qty of product Magento

I'm implementing custom sidebar cart of Magento, which will feature incrementation and decrementaton of products in this cart, refreshed in ajax.
AJAX is possible to work just with HTML, isn't working as return value is whole cart.
I'm adding 1 quantity of product using CartController: /checkout/cart/add/uenc/aHR0cDovL3BsYXkudGhlaGFwcHlwZWFyLm5ldC9zaG9wL2RyaW5rcw,,/product/586/
Is it possible to just remove 1 quantity of product? Do I have to create new custom function in CartController?
Thanks,
Adam
ANSWER:
you can call this link with
/checkout/cart/remove/id/ $ITEMID /uenc/aHR0cDovL3BsYXkudGhlaGFwcHlwZWFyLm5ldC9zaG9w/ (depending on your magento settings link could be different)
Copy into CartController.php
public function removeAction()
{
$cart = $this->_getCart();
$params = $this->getRequest()->getParams();
try {
if (isset($params['qty'])) {
$filter = new Zend_Filter_LocalizedToNormalized(
array('locale' => Mage::app()->getLocale()->getLocaleCode())
);
$params['qty'] = $filter->filter($params['qty']);
}
$product = $this->_initProduct();
$related = $this->getRequest()->getParam('related_product');
/**
* Check product availability
*/
$id = (int) $this->getRequest()->getParam('id');
$items = $cart->getItems();
foreach ($items as $item) {
if ($item->getProduct()->getId() == $id) {
if( $item->getQty() == 1 ){
$cart->removeItem($item->getItemId())->save();
}
else if($item->getQty() > 1){
$item->setQty($item->getQty() - 1);
$cart->save();
}
break;
}
}
$this->_getSession()->setCartWasUpdated(true);
/**
* #todo remove wishlist observer processAddToCart
*/
Mage::dispatchEvent('checkout_cart_add_product_complete',
array('product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse())
);
if (!$this->_getSession()->getNoCartRedirect(true)) {
if (!$cart->getQuote()->getHasError()){
//$message = $this->__('%s was added to your shopping cart.', Mage::helper('core')->escapeHtml($product->getName()));
//$this->_getSession()->addSuccess($message);
}
$this->_goBack();
}
} catch (Mage_Core_Exception $e) {
if ($this->_getSession()->getUseNotice(true)) {
$this->_getSession()->addNotice(Mage::helper('core')->escapeHtml($e->getMessage()));
} else {
$messages = array_unique(explode("\n", $e->getMessage()));
foreach ($messages as $message) {
$this->_getSession()->addError(Mage::helper('core')->escapeHtml($message));
}
}
$url = $this->_getSession()->getRedirectUrl(true);
if ($url) {
$this->getResponse()->setRedirect($url);
} else {
$this->_redirectReferer(Mage::helper('checkout/cart')->getCartUrl());
}
} catch (Exception $e) {
$this->_getSession()->addException($e, $this->__('Cannot add the item to shopping cart.'));
Mage::logException($e);
$this->_goBack();
}
}

Magento - remove one quantity from cart

I am trying to remove just one qty from my cart rather than all, but to no avail.
Can anybody help?
Here is the code I have got so far...
require_once 'app/Mage.php';
Mage::app("default");
Mage::getSingleton("core/session", array("name" => "frontend"));
$session = Mage::getSingleton("customer/session");
$yourProId = $_POST['prodID'];
$qty = 1;
foreach (Mage::getSingleton('checkout/session')->getQuote()->getItemsCollection() as $item) {
if ($yourProId == $item->getProductId()) {
Mage::getSingleton('checkout/cart')->removeItem($item->getId())->save();
}
}
UPDATE: Here is the code that works, thanks to R.S. for this!
$yourProId = $_POST['prodID'];
$qty=1;
$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
foreach ($items as $item) {
if ($item->getProduct()->getId() == $yourProId) {
$qty = $item->getQty() - 1; // check if greater then 0 or set it to what you want
if($qty == 0) {
Mage::getSingleton('checkout/cart')->removeItem($item->getId());
} else {
$item->setQty($qty);
}
$cartHelper->getCart()->save();
break;
}
}
Try
$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
foreach ($items as $item) {
if ($item->getProduct()->getId() == $yourProId) {
if( $item->getQty() == 1 ){
$cartHelper->getCart()->removeItem($item->getItemId())->save();
}
else if($item->getQty() > 1){
$item->setQty($item->getQty() - 1)
$cartHelper->getCart()->save();
}
break;
}
}
Take a look # /app/code/core/Mage/Checkout/controllers/CartController.php
See http://www.magentocommerce.com/boards/viewthread/30113/
You can alter or remove qty using $quoteItem->setData('qty', $avl_qty);
Please refer to code for more help.
$quoteItem = $observer->getEvent()->getQuoteItem();
$avl_qty = 1;
if ($avl_qty == '0') {
$quoteItem->getQuote()->removeItem($quoteItem->getItemId());
throw new LocalizedException(__("This product is currently out of stock."));
}
elseif ($order_qty > $avl_qty) {
$quoteItem->setData('qty', $avl_qty);
$this->_cart->save();
$this->messageManager->addNoticeMessage('Sorry we have only '.$avl_qty.' qty of this product available');
}
else {
}
For Magento 2
you can utilize
https://yourdomain.com/rest/V1/carts/mine/items
API with Auth token and Body
{
"cartItem": {
"item_id": 49388,//item_id not SKU
"qty": 1, //This will overwrite quantity
"quote_id": {{QuoteId}}
}
}

Resources