0

in Magento 2 I am trying to get below details of the product from the customer cart

  • Name
  • ID
  • Price
  • Brand
  • Category
  • Variant
  • Quantity

This process I added in observer during customer proceed to checkout

I am stuck at trying to get the brand, variant, and quantity for the item that is currently in the cart, below are the code I currently use at CheckShoppingCartObserver.php

<?php

namespace Shop\Product\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;

class CheckShoppingCartObserver implements ObserverInterface
{
    private $gtmLogger;
    protected $customerSession;

    public function __construct(
        \Wowshop\Custom\Model\GoogleTagManager\Logger $gtmLogger,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Checkout\Model\Cart $cart,
        \Magento\Catalog\Model\CategoryFactory $categoryFactory,
        \Shop\Product\Helper\Data $productHelper,
        \Magento\Framework\Pricing\Helper\Data $priceHelper
    ){
        $this->gtmLogger = $gtmLogger;
        $this->customerSession = $customerSession;
        $this->cart = $cart;
        $this->categoryFactory = $categoryFactory;
        $this->productHelper = $productHelper;
        $this->priceHelper = $priceHelper;
    }

   public function execute(Observer $observer)
   {
        $products = [];

        try {
            $this->gtmLogger->info("------------------ customer proceed to checkout observer-----------------");
            $items = $this->cart->getItems();

            foreach ($items as $item) {
                $product = $item->getProduct();

                // get category
                $categoryIds = $product->getCategoryIds();
        
                foreach($categoryIds as $category_key => $category_id){
                    $category = $this->categoryFactory->create()->load($category_id);
                    $categories_name[$category_key] = $category->getName();
                }
        
                $categories_full = implode($categories_name," - ");
                // end get category

                // get cashback and price

                $cashBack = $this->productHelper->getCashBack($product);
                $allCashBack = $this->productHelper->getAllProductCashback($product);
                $productPrice = $product->getFinalPrice();

                $data = [];
                if(!empty($product)) {
                    $data[] = $cashBack;
                }
                $label = $price = '';
                if(!empty($allCashBack)) {
                    
                    if(count($allCashBack) == 1){
                        $label .= $allCashBack[0] . '%' ;
                        $price .= $this->priceHelper->currency(round(($productPrice*$allCashBack[0])/100, 0),true,false);
                    } else{
                        $i = 0;
                        foreach($allCashBack as $promo) {
                            $i++;
                            if($i < count($allCashBack)){
                                $label .= $promo . '% + ' ;
                                $price .= $this->priceHelper->currency(round(($productPrice*$promo)/100, 0),true,false) . ' + ';
                            } else{
                                $label .= $promo . '%' ;
                                $price .= $this->priceHelper->currency(round(($productPrice*$promo)/100, 0),true,false);
                            }
                            
                        }
                    }
                }

                $percentage_cashback = $label;
                $monetary_cashback = $price;
                
                // end get cashback and price

                // get shipping details
                $shipping_details = $this->productHelper->getShippingDetails($product);
                $east_pos = strpos($shipping_details, "East");
                $wm = trim(substr($shipping_details, 0, $east_pos-1));
                $wm = str_replace("\t"," ", $wm);
                $em = substr($shipping_details, $east_pos, strlen($shipping_details));
                $em = str_replace("\t"," ", $em);

                // end get shipping details

                $product = [
                    'name' => $product->getName(),
                    'id' => $product->getId(),
                    'price' => $product->getFinalPrice(),
                    'brand' => 'n/a',
                    'category' => $categories_full,
                    'variant' => 'n/a',
                    'quantity' => 1, // product level coupon/promo code used
                    'dimension17' => $product->getFinalPrice(), // sale price
                    'dimension18' => number_format($this->productHelper->getMarketPrice($product), 2), // market price
                    'dimension19' => $percentage_cashback . ' ('. $monetary_cashback .')', // cashback
                    'dimension20' => $wm, // shipping - west malaysia
                    'dimension21' => $em // shipping - east malaysia
                ];

                $products[] = $product;
            }

            
            $params['GTM_EVENT']=array(
                'event'=>'ecommerceCheckout',
                'eventDetails.category'=>'Ecommerce',
                'eventDetails.action'=>'Checkout Step 1',
                'eventDetails.nonInteraction'=>'false',
                'ecommerce'=> [ 
                    'currencyCode' => 'MYR',
                    'checkout' => [
                        'actionField' => [
                            'step'=> 1
                        ],
                        'products' => $products
                    ]
                ]
            );

            $this->gtmLogger->info("gtm event proceed to checkout " . print_r($params['GTM_EVENT'], true));

        }catch (\Exception $e) {
            $this->gtmLogger->debug("exception message:" . print_r($e->getMessage(), true));
        }
        
    }


}


?>

as you can see on the code above, there is a way to call the product name such as $product->getName() and product id such as $product->getId() but there is no way to get the quantity of an item in the customer's cart

is there any Magento existing function to get this data, and if there is, is there any documentation that I can refer to learn more about this.

any help is kindly appreciated, thank you

2 Answers 2

1

You can get the quantity of an item in the customer's cart by this method

$items = $this->cart->getItems();
foreach ($items as $item) {
    .........
    $product = $item->getProduct();
    $qty = $item->getQty()
    .........
}
2
  • Thank you for this answer, I am able to get the quantity using this details Feb 22 at 8:42
  • For additional info that I do not manage to get before I already able to get now, refer to the below answer on how I found the solution to this problem Feb 22 at 8:43
0
  • Name

$product->getName()

  • SKU

$product->getSku()

  • Price

$product->getFinalPrice()

Brand

Depends on attribute being registered in the system, in this case, its g_brand_name

public function getBrand($product)
{
    $brand = 'n/a';
    
    $objectManager =  \Magento\Framework\App\ObjectManager::getInstance();      
    $storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
    $currentStoreId = $storeManager->getStore()->getStoreId();

    if($product->getResource()->getAttribute('g_brand_name')->setStoreId($currentStoreId)->getFrontend()->getValue($product)){
        $brand = $product->getResource()->getAttribute('g_brand_name')->setStoreId($currentStoreId)->getFrontend()->getValue($product);
    }

    return $brand;
}

Category

public function getCategory($product)
{
    $categoryIds = $product->getCategoryIds();
    $category_name = 'n/a';
    $category_list = [];

    foreach($categoryIds as $category_key => $category_id){
        $category = $this->_categoryFactory->create()->load($category_id);
        $category_list[] = $category->getName();

    }

    if(isset($category_list) && !empty($category_list)){
        $category_name = implode(",", $category_list);
        $category_name = addslashes($category_name);
    }

    return $category_name;
}

Variant

public function getVariant($product)
{
        $variant = 'n/a';

        if($product->getTypeId() == \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE){

            // Retrieve used product attributes
            $productAttributeOptions = $product->getTypeInstance()->getConfigurableAttributesAsArray($product);

            $variant = [];

            foreach ($productAttributeOptions as $key => $value) {

                $tmp_option = $value['values'];
                if(count($tmp_option) > 0)
                {
                    $variant_name = $value['label']; 
                    foreach ($tmp_option as $tmp) 
                    {
                        $variant[$variant_name][] = $tmp['label'];
                    }
                }
            }

            $variant = json_encode($variant);

        }

        return $variant;
}

Quantity

$item->getQty();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.